1

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,
       },
      ]);
    });
  });
};
3
  • I didn't get deep into your code but take into consideration that setState (with hooks as well) is asynchronous. Commented Aug 2, 2020 at 9:09
  • Try this: jsfiddle.net/y1uLpq5d Does it work? Commented Aug 2, 2020 at 9:17
  • I am actually using functional components and hooks Commented Aug 2, 2020 at 9:25

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

Use map method instead of filter to loop through a list.

Best Regards!

1 Comment

I tried the same thing with map and the result is same.

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.