1

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)

  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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.