I am trying to fetch data array with hooks but it throws an error. However, when using setState it will work.
I am getting the books data from googleapis like this:
const [books, setBooks] = useState([])
const searchBook = (event) => {
event.preventDefault()
request
.get('https://www.googleapis.com/books/v1/volumes')
.query({q:searchField})
.then((data)=> {
console.log(data.body.items)
//with setState it works
this.setState({books: [...data.body.items]})
//with hooks it is not working
setBooks([...data.body.items])
console.log(books)
})
}
Using Hooks will throw an error Objects are not valid as a React child
Any idea how to make it work with hooks?
Edited
I added a link codesandbox
For example, if I type dog in the input and click search, I see my console.log(data.body.items) but console.log(books, "books") is an empty array.
object. It will be great if you add the response or a link using Codesandbox or Codepen.