Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Firestore database infinite loop React Js

I have my react js app linked to cloud Firestore and I’m trying to display the objects on my js file.

I have only 1 object in my Firestore but it keeps reading in a loop and i cant figure out why.

Code from explore.js (display objects from Firebase)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  const [nft,setNft]=useState([])
  const getNft= async()=>{
     const nft = await fs.collection('NFT').get();
     const nftArray=[];
     for (var snap of nft.docs){
       var data = snap.data()
        data.ID = snap.id;
        nftArray.push({
          ...data
        })
        if(nftArray.length===nft.docs.length){
          setNft(nftArray);
        }
      }
    }
    useEffect(()=>{
      getNft();
    })}
        {nft.length > 0 && (
            <div>
                <div className='cardContainer'>
                    <Nft nft={nft}/>
                </div>
            </div>
        )}
        {nft.length < 1 && (
            <div className='loading'>Loading products..</div>
        )}

Infinite loop console

>Solution :

useEffect has a "trigger" property.

ex:

Will run on every render

useEffect(() => {
  //do something
});

Will run only once

useEffect(() => {
  //do something
}, []);

Will run when given properties changes

useEffect(() => {
  //do something
}, [someProperty, someOtherProperty]);

In your case, you are calling the async function, the async function updates the state, and causes a rerender. Since you don’t have any trigger (or empty array) added to the useEffect, it will run again, and again, and again.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading