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

Why am I getting too many renders when trying to setState?

Here is my code. I’m grabbing data from firebase and placing it into my groupDataMap.

const Home = () => {
    
    const [memberInfo, setMemberInfo] = useState('');
    const auth = getAuth();
    const user = auth.currentUser;
    const memberId = auth.currentUser.uid
    const db = getDatabase();
    const dbRef = ref(db, 'groups');
    let groupDataMap = {};

    //get group name's if member_id(user) matches member id
    onValue(dbRef, (snapshot)=> {
        const data = snapshot.val();

        for(var key in data){
            if(data.hasOwnProperty(key)){
                const groupname = data[key]
                groupDataMap = groupname
            }
        }
    })
    setMemberInfo(groupDataMap)


I’m using memberInfo to populate a <li> element in my return:

 return (
        <div>
            <div class="brand">
                <h1>Headline</h1>
                <p>paragraph</p>
            </div>

            <ul class="list-group container-fluid">
                <li class="list-group-item">
                {memberInfo}
                </li>
            </ul>
        </div>
    );

Am I not just setting the state once?

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

>Solution :

Am I not just setting the state once?

No, setMemberInfo is going to be called again and again, so that the component renders infinitely.

Read about useEffect hook.

    const [memberInfo, setMemberInfo] = useState('');
    const auth = getAuth();
    const user = auth.currentUser;
    const memberId = auth.currentUser.uid

    useEffect(() => {
        const db = getDatabase();
        const dbRef = ref(db, 'groups');
        let groupDataMap = {};

        //get group name's if member_id(user) matches member id
        onValue(dbRef, (snapshot)=> {
            const data = snapshot.val();

            for(var key in data){
                if(data.hasOwnProperty(key)){
                    const groupname = data[key]
                    groupDataMap = groupname
                }
            }
        })
        setMemberInfo(groupDataMap)

    }, []); 

Tip: Refer this similar case to your question

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