React useEffect is not being called

Viewed 50

I am trying to set up a system where when the system mounts onSnapshot is not called. However, once system has mounted useEffect can run onSnapshot, if something in the database changes. However, even when I add something in the database onSnapshot is not called in the useEffect, it doesn't even gets in the useEffect block.

 useEffect(() => {
        if (isMounted.current) {
            console.log("Dashboard mounted");
             onSnapshot(collection(db, 'announcements'), async (snapshot) => {
                console.log("BRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR")
                let oldData = announcementsData;
                let temp = snapshot.docs.map(doc => doc.data());
                // sort temp by id in descending order
                temp.sort((a, b) => {
                    return b.id - a.id;
                }
                );
                dispatch(addAnnouncements(temp));

                // console.log(oldData.length !== temp.length && oldData.length !== 0)
                if (oldData.length !== temp.length && oldData.length !== 0) {
                    await schedulePushNotification(temp[0].title, temp[0].description);
                }
                setAnnouncementsData(temp);

            })
        }
        else {
            isMounted.current = true;
        }
    }, []);
1 Answers

Remove the if (isMounted.current) check from your useEffect since it doesn't have any effect on mounting the dashboard, especially since useEffect function only gets called once due to the empty dependency array:

 useEffect(() => {
    
            console.log("Dashboard mounted");
             onSnapshot(collection(db, 'announcements'), async (snapshot) => {
                console.log("BRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR")
                let oldData = announcementsData;
                let temp = snapshot.docs.map(doc => doc.data());
                // sort temp by id in descending order
                temp.sort((a, b) => {
                    return b.id - a.id;
                }
                );
                dispatch(addAnnouncements(temp));

                // console.log(oldData.length !== temp.length && oldData.length !== 0)
                if (oldData.length !== temp.length && oldData.length !== 0) {
                    await schedulePushNotification(temp[0].title, temp[0].description);
                }
                setAnnouncementsData(temp);

            })
            isMounted.current = true
        
    }, []);
Related