'forEach loop returning the value but my react useState value only returning one array obj

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



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1