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

127
Views
.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 answers
Answer question

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 Report

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 Report

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 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!