Home > other >  I can't print multiple documents from FireStore
I can't print multiple documents from FireStore

Time:08-20

I'm able to pull all documents in a collection from Firestore and print each one by one using console.log() command. But when I want to print these documents to the screen, only the most recent document from the database is printed.

here is my code.

import React, {useState, useEffect, createElement} from 'react'
import styled from 'styled-components'
import { db } from '../firebase';
import { collection, query, where, getDocs } from "firebase/firestore";

function Dashboard () {

let [alims, setAlims] = useState([]);
    const getAlim = async() => {
        const colRefBuy = collection(db, "alim");
        const docsSnap = await getDocs(colRefBuy);
        docsSnap.forEach(docBuy => {
            let dataRaw = docBuy.data();
            let datas = dataRaw.name  ' : '  dataRaw.value  'TL, '  dataRaw.price ' Adet'; 
            setAlims([...alims, datas]);
        })
    } 
useEffect(() => {
        getSatim();
    }, []);


return (
    <Container>
    <BackgroundImage>
        <img src='/images/home-background.png' alt='bg'/>
    </BackgroundImage>
            <Right>
                <h2>Alımlar</h2>
                <div>
                <span>{alims.map((e) => 
                    <span>{e}</span>
                    )}</span>
                </div>
            </Right>
    </Container>
  )
}

but as I said, it only prints the Tesla document, which is the last among 3 documents.

enter image description here

CodePudding user response:

You should first map an array containing data from all the documents and update the state only once instead of updating it for every document in the loop. Try refactoring the code as shown below:

let [alims, setAlims] = useState([]);

const getAlim = async () => {
  const colRefBuy = collection(db, "alim");
  const docsSnap = await getDocs(colRefBuy);

  const data = docsSnap.docs.map((d) => {
    return dataRaw.name   ' : '   dataRaw.value   'TL, '   dataRaw.price   ' Adet'
  })

  setAlims(data);
}
  • Related