Unable fetch data firestore, article.map is not function

178 Views Asked by At

I am not able to map over BlogsOverviews components, It says article.map is not function, help me out with this

MainContent.jsx:28 Uncaught TypeError: Cannot read properties of undefined (reading 'map') at MainContent (MainContent.jsx:28:1) at renderWithHooks (react-dom.development.js:14985:1) at mountIndeterminateComponent (react-dom.development.js:17811:1) at beginWork (react-dom.development.js:19049:1) at HTMLUnknownElement.callCallback (react-dom.development.js:3945:1) at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:1) at invokeGuardedCallback (react-dom.development.js:4056: beginWork$1 (react-dom.development.js:23964:1) at performUnitOfWork (react-dom.development.js:22776:1 at workLoopSync (react-dom.development.js:22707:1)

    const [articles, setArticles] = useState([]);
      async function name(){
        const querySnapshot = await getDocs(collection(db, "body"));
        querySnapshot.forEach((doc) => {
          let items = doc.data();
          setArticles({items: items});
        });
      }
  
    useEffect(() => {
       name();
    }, [])
  
  return (
    // <!-- Main post Starts -->
    <div class="container-sm d-flex py-3 main_post">
        <div class="stories">
            <h5>All Story</h5>
            <hr/>
        {articles.items.map(({ title, contnent, date, author }) => (
            <BlogsOverviews title={title} contnent={contnent} date={date} author={author}/>
        ))}
        </div>
        <div class="new">
            <h5>Popular</h5>
            <hr />
            <HeadLines text="01"/>
            <HeadLines text="02"/>
            <HeadLines text="03"/>
            <HeadLines text="04"/>
            <About />
        </div>
    </div>
  )
}```
1

There are 1 best solutions below

0
On

I would suggest changing how you fetch and map the documents as you're using it on useEffect. Firestore has built in realtime listeners which fits your use-case. See code below:

async function name() {
  const bodyRef = query(collection(db, 'users'))
  onSnapshot(bodyRef, (snapshot) => {
    setArticles(snapshot.docs.map(doc => ({
      items: doc.data()
    })))
  })
}

useEffect(() => {
  name();
},[])

then for rendering:

{articles.map((article) => (
    <BlogsOverviews
        title={article.items.title}
        contnent={article.items.contnent}
        date={article.items.date}
        author={article.items.author}
    />
))}

For more information, checkout Get realtime updates with Cloud Firestore