1
const user = useSelector((state) => state.user);
const [allPost, setAllPost] = useState([]);

const getAllPost = async () => {
  const q = query(collection(db, "posts", "post", user.user.email));
  const querySnapshot = await getDocs(q);
  querySnapshot.forEach((doc) => {
    console.log(doc.data());
    const newPost = doc.data();
    setAllPost([...allPost, newPost]);
  });
};

useEffect(() => {
  getAllPost();
}, []);

I have four documents in my firestore but setState only returning one although using forEach loop i can see all four object

Phil
  • 157,677
  • 23
  • 242
  • 245

1 Answers1

5

The problem is that each time you use

setAllPost([...allPost, newPost]);

allPost is still the previous value because state value updates are asynchronous; allPost won't contain the new value until the next render.

You can either use the functional version of the state setter...

querySnapshot.forEach(doc => {
  setAllPost(prev => prev.concat(doc.data()));
});

or simply build up a separate array and set them all at once

setAllPost(querySnapshot.docs().map(doc => doc.data()));

Personally, I'd prefer the latter.

Phil
  • 157,677
  • 23
  • 242
  • 245