Home > Software engineering >  Why am I getting too many renders when trying to setState?
Why am I getting too many renders when trying to setState?

Time:04-27

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 >
                <h1>Headline</h1>
                <p>paragraph</p>
            </div>

            <ul >
                <li >
                {memberInfo}
                </li>
            </ul>
        </div>
    );

Am I not just setting the state once?

CodePudding user response:

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

CodePudding user response:

You will have to use react's useEffect hook to set state.

Use this link for reference

  • Related