kirimi
kirimi

Reputation: 1400

react fetching data array with setState is working but not with hooks

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.

Upvotes: 0

Views: 75

Answers (2)

Sohail Ashraf
Sohail Ashraf

Reputation: 10569

You are getting empty result in console.log(books, "books") because setBooks is an async function.

Try this.

const searchBook = (event) => {
        event.preventDefault()
        request
          .get('https://www.googleapis.com/books/v1/volumes')
          .query({q:searchField})
          .then((data)=> {
            setBooks([...data.body.items])
          })
      }

Live Example:

Edit adoring-almeida-59oys

Upvotes: 1

emeraldsanto
emeraldsanto

Reputation: 4741

I was wondering why you were doing this

setBooks([...data.body.items]);

instead of this

setBooks(data.body.items);

Because you don't need to create a new array from the existing data.body.items which is already an array. So I tried it in the codesandbox you provided and that seems to fix the problem.

Upvotes: 0

Related Questions