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

135
Vistas
.map() is not defined as a function

I am trying to use ".map()" to map documents which I'm getting from firebase. However it says .map() is not a function. Code is below. Basically I'm trying to fetch my firebase data, then render each doc as a element.

 <div{posts.map((doc) => <p>{doc.data().text}</p>)}</div>

How I decleared useState posts variable:

  const [posts, setPosts] = useState([]);

How I set useState posts variable:

useEffect(() => {
  db.collection('posts').onSnapshot((querySnapshot) => {
    setPosts(querySnapshot);

  });
})

Also, I tried using ".forEach". I can "console.log" the each documents by using ".forEach" but ".forEach" doesn't allow to return elements.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

first log your querySnapshot and see whether it's an array, then you should check if posts' array is not null. try this :

<div{posts.length > 0 ? posts.map((doc) => <p>{doc.data().text}</p>) : null}</div>
about 4 years ago · Juan Pablo Isaza Denunciar

0

.forEach can be used over Sets, Maps and Arrays, whereas .map can be used only over arrays. So, it is likely that the querySnapshot is returning a set that is updated on posts, since posts is now a Set, map is unable to iterate and return values from the iterable posts. To overcome this, you could convert the Set to an array before updating the state.

useEffect(() => {
  db.collection('posts').onSnapshot((querySnapshot) => {
    let querySnapshotToArray = Array.from(querySnapshot)
    setPosts(querySnapshotToArray);

  });
})

Now that the post is an array, you could map over it and return the required values.

about 4 years ago · Juan Pablo Isaza Denunciar

0

when react component render the first time posts is null or undefined so .map was undefined you need to use Optional chaining, represented by ?. in JavaScript, which is a new feature introduced in ES2020.

 <div{posts?.map((doc) => <p>{doc?.data()?.text}</p>)}</div>
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