Home > database >  React Cloud Firestore Not Fetching Data Properly
React Cloud Firestore Not Fetching Data Properly

Time:12-04

I need to fetch all data from the collection but instead only getting one document. I will be grateful for you support. Below, I present the screenshots and code snippet regarding my concern. enter image description here enter image description here

import './App.css';
import db from './firebase';
import React,{useState,useEffect} from 'react';

function App() {
  const [accounts,setAccounts]=useState([])
  const fetchAccounts=async()=>{
    const response=db.collection('accounts');
    const data=await response.get();
    data.docs.forEach(item=>{
     setAccounts([...accounts,item.data()])
    })
  }

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

  return (
    <div className="App">
      {
        accounts && accounts.map(account=>{
          return(
            <div>
              <h1>Example</h1>
              <h4>{account.date}</h4>
              <p>{account.email}</p>
            </div>
          )
        })
      }
    </div>
  );
}

export default App;

CodePudding user response:

Set state functions in React are async. It means that your values are not updated immediately.

So when you update your state in a loop, each time it updates the initial value of the state and because of that at the end of the loop, only 1 item is added to the array.

In order to fix the bug, you should use another variable and set your state after the loop:

import React, { useState, useEffect } from 'react';
import './App.css';
import db from './firebase';

function App() {
  const [accounts, setAccounts] = useState([]);

  const fetchAccounts = async () => {
    const response = db.collection('accounts');
    const data = await response.get();
    const newAccounts = data.docs.map(item => item.data());
    setAccounts(newAccounts);
  }

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

  return (
    <div className="App">
      {
        accounts && accounts.map(account => {
          return(
            <div>
              <h1>Example</h1>
              <h4>{account.date}</h4>
              <p>{account.email}</p>
            </div>
          )
        })
      }
    </div>
  );
}

export default App;
  • Related