Firebase 9,real time database / react native with expo.
issue: I can not unsubscribe from firebase RTD onChange event listener.
The docs say: "Calling off() on a parent listener does not automatically remove listeners registered on its child nodes; off() must also be called on any child listeners to remove the callback." Firebase docs
error: When I try using .off
on the reference I get reference.off() is not a function
const db = getDatabase();
const reference = ref(db, "users/" props.userId);
const updateScore = (snapshot) => {
if (snapshot.val() !== null) setHighScore(highscore);
};
useEffect(() => {
if (props.userId === "") props.navigation.navigate("Auth");
else onValue(reference, updateScore);
// throws error reference.off() is not a function
return () => reference.off();
}, [props.userId]);
I've also tried reference.unsubscribe()
and reference.removeEventListener(updateScore)
with no luck. They both trigger the same error reference.**** is not a function
.
Without clearing up this event listener I have a memory leak in my application.
CodePudding user response:
For v9, when you call onValue
it returns an unsubscribe function, as shown in the reference docs for onValue
. So to unsubscribe:
useEffect(() => {
if (props.userId === "") props.navigation.navigate("Auth");
else return onValue(reference, updateScore);
}, [props.userId]);