is it possible to call a firebase function onValue() in another onValue() if yes how to do

Viewed 18

technologies used: React Native / Expo / Firebase

I explain to you, I recover a list of key with my first onValue, in this one I forEach for each key and in this one I make another onValue in order this time to recover the information of the keys, but I realize that it creates a problem, one event calls another and it creates duplicate calls. Moreover I could not intervene on the second listening to delete it since it is only initialized locally, so how can I call this in the right way? thank you in advance for your answers, I'm new to react native with firebase!

Here is a snippet of the code:

  useFocusEffect( // first time the screen is loaded, the gardener list is empty, so we need to get the gardener list from firebase

React.useCallback(() => {
    setGardeners([])

    const gardenerRef = ref(db, 'users/' + auth.currentUser.uid + '/gardeners');
    const gardenerListener = onValue(gardenerRef, (snapshot) => {
        const data = snapshot.val();
        if (data != null) {
            setIsFirst(false)
            Object.keys(data).forEach(e => {
                const temp = ref(db, 'gardeners/' + e);
                onValue(temp, (snapshot) => {
                    const data = snapshot.val();
                    if (data != null && data.metadata != undefined) {
                        setGardeners(gardeners => [...gardeners, { id: e, name: data.metadata.name, isIrrig: data.irrig }]);
                    }
                })
                gardeners.length > 0 ? setCurrentGardener(gardeners[0].id) : setCurrentGardener("")
                setC(currentGardener != "" ? currentGardener : "")
            })
        } else {
            setIsFirst(true)
        }
    })

and here is the way i turn off the event during disassembly, for me it looks correct, now if you think i did it wrong, don't hesitate

            return () => {
           setGardeners([])
           off(gardenerRef, gardenerListener)
           // console.log("unmounted")
       }

}, []))
0 Answers
Related