2

What is wrong in what i am doing, i am getting collection snapshot, looping through it and push it to the state then use that state to render some list items but i get that error: Unhandled Rejection (TypeError): Cannot read property 'map' of undefined

Code:

const [books, setBooks] = useState([]);
db.collection('books').get()
   .then(snapshot => snapshot.forEach(doc => {
      setBooks([...books, doc.data()])
}))

return (
  books.map(return some jsx)
)
3
  • 1
    have you tried this in return books && books.map(return some jsx) ? Commented Sep 26, 2020 at 7:13
  • yes i tried it but never worked! @shubhamjha Commented Sep 26, 2020 at 7:14
  • may be you could try with empty value like setBooks([]) in forEach and log the doc and doc.data() Commented Sep 26, 2020 at 7:17

1 Answer 1

1

You are doing too many setState. Why not simply do it once?

const [books, setBooks] = useState([]);
db.collection('books')
  .get()
  .then(snapshot => snapshot.map(s => s.data())
  .then(data => setBooks(data))
}))

return (
  books.map(b => <div>{book stuff here}</div>)
)
Sign up to request clarification or add additional context in comments.

6 Comments

unfortunately, i get that error Unhandled Rejection (TypeError): snapshot.map is not a function The same error that pushed me to use forEach
@CodeEagle, that only means your db query is not returning an array. Log the snapshot variable and see what's in there.
@CodeEagle, this is probably what you want stackoverflow.com/a/52101894/1693859
Debug it. Put a debugger statement inside the then(snapshot => { debugger }) and look at the devtool to see what's inside of it.
it worked finally, thank you you saved me too much rerendering!
|

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.