When working with Firebase
and React
, in order to fetch data based on state changes or on inner database changes (from another user for example), I often rely on pieces of code like this one:
useEffect(() => {
const getGamesInSelectedGroup = () => {
if (!state.currentGroup) {
return
}
const db = getDatabase();
const resp = ref(db, `/games/${state.currentGroup.name}`);
onValue(resp, (snap) => {
if (snap.exists()) {
const data = snap.val()
const games = Object.keys(data).map(k => ({id: k, group: state.currentGroup.name, ...data[k]}))
setState((prev) => ({
...prev,
games: games,
isLoaded: true,
}));
return
}
setState((prev) => ({
...prev,
games: null,
isLoaded: true,
}));
toast.warning("no data for " + state.currentGroup.name)
})
}
getGamesInSelectedGroup();
}, [state.currentGroup])
However, I am wondering if, whenever state.currentGroup
changes, a new listener to /games/${state.currentGroup.name}
is created? If so, is there a mean to unsubscribe to previous listener before creating a new one?
I have thinking about replacing onValue
by a get
call, still conditioned on state.currentGroup
and using onValue
outside useEffect
to reflect “inner” database change.