Mega_Noob
Mega_Noob

Reputation: 214

How do I render Firestore collection using the Map function in React?

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

Upvotes: 0

Views: 512

Answers (1)

Pushkin
Pushkin

Reputation: 3604

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()])

Upvotes: 1

Related Questions