Reputation: 71
I have a state where I store all the uuids of the posts. I am retrieving the uuids of the posts in useEffect() from firebase and looping through the array of uuids and retrieving all the posts that the user made but the posts state is returning an empty array.
useEffect(() => {
getData();
}, []);
const getData = () => {
setPosts([]);
setPostuuids([]);
firebase
.firestore()
.collection("users")
.doc(uid)
.get()
.then((doc) => {
setPostuuids(doc.data().posts);
});
postuuids.filter((postuuid) => {
firebase
.firestore()
.collection("posts")
.doc(postuuid)
.get()
.then((doc) => {
const image = doc.data().image;
const text = doc.data().text;
const userid = doc.data().uid;
const timestamp = doc.data().timestamp;
const username = doc.data().username;
const uuid = doc.data().uuid;
const name = doc.data().name;
const avatar = doc.data().avatar;
setPosts((prevPosts) => [
...prevPosts,
{
image: image,
timestamp: timestamp,
text: text,
name: name,
userid: userid,
uuid: uuid,
username: username,
avatar: avatar,
},
]);
});
});
};
Upvotes: 1
Views: 198
Reputation: 451
your postuuids.filter run before request completed, so postuuids is empty. you should use another useEffect() for postuuids.map():
useEffect(() =>{
postuuids.map((postuuid) => {
firebase
.firestore()
.collection("posts")
.doc(postuuid)
.get()
.then((doc) => {
const image = doc.data().image;
const text = doc.data().text;
const userid = doc.data().uid;
const timestamp = doc.data().timestamp;
const username = doc.data().username;
const uuid = doc.data().uuid;
const name = doc.data().name;
const avatar = doc.data().avatar;
setPosts((prevPosts) => [
...prevPosts,
{
image: image,
timestamp: timestamp,
text: text,
name: name,
userid: userid,
uuid: uuid,
username: username,
avatar: avatar,
},
]);
});
});
};
},[postuuids])
Upvotes: 1