Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

280
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda