I never find a solution for my useEffect probleme :
I'm useing firebase and create a listener (onSnapshot) on my database to get the last state of my object "Player" I can get when the states currentGroup and currentUser are available
const [currentGroup, setCurrentGroup] = useState(null)
const [currentUser, setCurrentUser] = useState(null)
const [currentPlayer, setCurrentPlayer] = useState(null)
const IDefineMyListener = () =>{
return firebase.doc(`group/${currentGroup.id}${users/${currentUser.id}/`)
.onSnpashot(snap =>{
//I get my snap because it changed
setCurrentPlayer(snap.data())
})
}
Juste above, i call a useEffect when the currentGroup and currentUser are available and (IMPORTANT) if I didn't already set the currentPlayer
useEffect(() => {
if (!currentGroup || !currentUser) return
if (!currentPlayer) {
let unsubscribe = IDefineMyListener()
return (() => {
unsubscribe()
})
}
},[currentGroup,currentUser])
As you can think, unsubscribe() is called even if the IDefineMyListener() is not redefined. In other words, when currentGroup or currentUser changes, this useEffect deleted my listener whereas I NEED IT.
How can i figure out ?!
PS :if I remove if (!currentPlayer), of course it works but will unlessly get my data
PS2 : If I remove the unsubscribe, my listener is called twice each time.