0

I'm having a very hard time understanding how can I render data from a firestore collection. Here is what I am doing so far: In /services/firestoreQueries:

const generateWishlist = (user) => {

    return db.collection('wishlist').where("username", "==", user.uid).get()

}

In my component file:

const ItemList = () => {
const {currentUser} = useAuth()
const [list, setList] = useState([])

useEffect(() => {
    generateWishlist(currentUser).then((snapshot) => {
        snapshot.docs.forEach((doc) => (

            setList(prevState => ({
                list: [...prevState.list, doc.data()]
            }))

            ))
    })
}, [currentUser])

console.log(list)


return (
    <div>
    <div>
        <h1>This is your wishlist!</h1>
    </div>
    </div>

)
}

I get a prevState.list is not iterable error.

If I comment out the code block inside snapshot and console.log(list), I get the data as expected, but when I try and map it, it says that list.map is not a function

Any idea why this may be happening? Any help would be appreciated! I've spent a little close to a whole day but no progress >.<

console.log when it returns data

[] ItemList.js:23 
{description: "i am testing", username: "CLmf7rX6I2YQsuAojqsJ3uWGqHD3", price: "10", item: "testing", live: true, …} ItemList.js:23 
{description: "i am testing", username: "CLmf7rX6I2YQsuAojqsJ3uWGqHD3", price: "10", item: "testing", live: true, …} ItemList.js:23
2
  • Post your console.log here Commented Jan 14, 2021 at 2:46
  • @Pushkin I have added my console.log in the details - please check. It returns data, but not in the list format, which is what I'd want Commented Jan 14, 2021 at 2:49

1 Answer 1

1

The error is not in .map, the error is in setList

You have created list as an array

const [list, setList] = useState([])

But when you're setting it, you're changing it to an object

setList(prevState => ({
   list: [...prevState.list, doc.data()]
}))

// list => {list: [...]}

Use setList as a hook and not as this.setState

setList(prev => ([...prev, doc.data()])
Sign up to request clarification or add additional context in comments.

2 Comments

Hi @Pushkin, thanks for your answer, but it gives me a TypeError: prevState.list is not iterable - see log below (anonymous function) src/components/ItemList.js:13 10 | generateWishlist(currentUser).then((snapshot) => { 11 | snapshot.docs.forEach((doc) => ( 12 | //setList(doc.data()) > 13 | setList(prevState => ([...prevState.list, doc.data()])) | ^ 14 | //console.log(doc.data()) 15 | )) 16 | })
Sorry, made a typo. Check now. It should have been just prevState, not prevState.list

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.