JS3
JS3

Reputation: 1847

How can I retrieve the array inside the firestore document?

The array doses is the one that I wanted to retrieve, however I keep getting an error that says that map is not a function. This is what it looks like in firebase:

enter image description here

codes to retrieve firestore data:

  useEffect(() => {
    const unsubscribe = firestore
      .collection("users")
      .doc(scanResult)
      .onSnapshot((snapshot) => {
        const arr = [];
        arr.push({
          ...snapshot.data(),
        });

        setUsers(arr);
      });

    return () => {
      unsubscribe();
    };
  }, []);

mapping the users array:

 {users && users.map((user) => (
      <li>{user.email}</li> // I could already retrieve the data that are not inside the doses array

     {/* get the doses array does not work */}
                  {users &&
                    users.doses.map((index) => {
                      <li>{index.selectedVaccine}</li>;
                    })}
    ))}

Upvotes: 0

Views: 32

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599956

Your doses field is not an array, but a map/object. An array has numeric, sequential keys, while a map/object has string keys.

If you want to loop over the keys of the field, you can do:

Object.keys(users.doses).map((key) => {
  <li>{user.doses[key]}</li>;
})}

If you instead just want to display the selectedVaccine value of the doses field, you'd do:

<li>{user.doses.selectedVaccine}</li>;

Upvotes: 1

Related Questions