0

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.

3
  • 1
    Hey kirimi, I think you are rendering an object. It will be great if you add the response or a link using Codesandbox or Codepen. Commented Feb 8, 2020 at 16:47
  • The error you get is thrown during rendering, not during setting of the value. Please add your rendering code (what is returned from the function you show us the content of). Commented Feb 8, 2020 at 16:49
  • @YashJoshi I will add a link thanks Commented Feb 8, 2020 at 17:05

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

4 Comments

thanks for the answer. I added a link it worked! but I notice that I have to click twice to update hooks. Do you know why this is happening?
Checking this issue
I have add the live example could you please try.
I am sorry for the late reply. Your answer works! but would like to know what is happening. Could you explain?
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.