Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

278
Views
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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!