Search code examples
reactjsfirebasereact-nativegoogle-cloud-firestoreexpo

fetch only one data of single document instead of all documents


I'm trying to fetch all data of documents inside the collection but unfortunately the code only fetch data of one single document.

    const Charities = ({navigation}) => {
        
        const [userData, setUserData] = useState([]);
    
    
        {/*fetch all documents from firestore*/}
        const fetchData = async()=>{
    
            const querySnapshot = await getDocs(collection(db, "Charities"));
            querySnapshot.forEach((doc) => {
             
              console.log(doc.id, " => ", doc.data());
              setUserData(doc.data())
            });               
    }
    
        useEffect(() => {
            fetchData()
           
        },[])



 function renderBody(){
        return(
            <View  
               
                 style={{
                // paddingBottom:100,
                 marginTop:10,
                 height:300,
                 alignItems:'center',
                 justifyContent:'center'
            }}>
               
             <Text>{userData?.Name}</Text>
           
             
            
            </View>
        )
    }


}

Between the code of fetching document from the official firebase website which only retrieve the info of the one document instead of all documents. So, I want the code to fetch all data of all documents that is what I'm expected. Your help is highly appreciated.

this is the photo of firestore which showing the charities collection that I want to fetch  all data of it

the code working correctly in console.log and fetch all documents data but when I set the code I got only one document data


Solution

  • You are logging each document to the console with forEach, but you are assigning a new doc.data to the same state each time. Instead, you can push each doc.data into an array and then update the state with the whole array.

    const fetchData = async () => {
        const querySnapshot = await getDocs(collection(db, "Charities"));
        const data = [];
        querySnapshot.forEach((doc) => {
          console.log(doc.id, " => ", doc.data());
          data.push(doc.data());
        });
        setUserData(data);
      };
    
    //or
    
    const fetchData = async () => {
      const querySnapshot = await getDocs(collection(db, "Charities"));
      querySnapshot.forEach((doc) => {
        console.log(doc.id, " => ", doc.data());
        setUserData(prevData => [...prevData, doc.data()]);
      });
    };