I'm having this error that says: TypeError: users.map is not a function What seems to be the problem with my codes?
const [users, setUsers] = useState([]);
const getData = async () => {
try {
const usersRef = firestore.collection("users").doc(id);
const doc = await usersRef.get();
if (!doc.exists) {
console.log("No such document!");
} else {
setUsers(doc.data());
}
} catch (err) {
console.log(err);
}
};
useEffect(() => {
getData();
}, []);
If I'll console.log(doc.data()), it does display the correct data. This error showed when I did this:
{users &&
users.map((index) => {
<li>{index.firstName}</li>;
})}
Update: the doc.data() was an object
Your usersRef is initialized like this:
const usersRef = firestore.collection("users").doc(id);
Since you include a doc call at the end there, the reference points to a single document in the users collection. So your doc is a single DocumentSnapshot and the doc.data() is the JSON for a single user's document, which explains why it doesn't have a map method (as the error message says).
If you want to load all users, you need to start with:
const usersRef = firestore.collection("users");
If you want to load a subset of all users, you can add a condition (.where(...)) to that.
If your getData loads the data you want: a single user, you'll probably want to pass it to your rendering code as an array of a single user with:
setUsers([doc.data()]); // Note the [] in there, those are new
If your code is only every supposed to be getting a single user, I'd recommend changing the names of your state hook and reference, and updating the rendering code to reflect that, as having users in that name implies there are multiple elements, and is just gonna lead to continued confusion.