Reputation: 683
I am trying to set up an authentication on my web application in React using firebase and Context API. I am using Context API since as long as I understood I cannot save my jwt token in local storage in order to not be vulnerable to XSS attack and at the moment I do not want to use Redux.
in my App.js I have:
const {setUserInfo} = useContext(userInfoContext);
useEffect(() => {
auth.onAuthStateChanged(user => {
if (user) {
setUserInfo({jwtToken: user.za});
} else {
setUserInfo({jwtToken: null});
}
console.log(user);
});
}, [setUserInfo]);
The methos "auth.onAuthStateChanged" is triggered every time I logged in or I logged out using firebase.auth.
The compiler tell me that to eliminate the warning I should have "[setUserInfo]" instead of "[]". However, doing as he say, the method setUserInfo is executed twice. There is a better way to achieve the result without a warning?
Upvotes: 0
Views: 366
Reputation: 357
Your problem is that you don't clean up your effect when it is recomputed. As soon as you add setUserInfo
to the dependency array, the effect is executed whenever its value changes. This means that you could potentially register many auth.onAuthStateChanged
if the value of setUserInfo
changes.
auth.onAuthStateChanged
returns an unsubscribe function. You can simply return this function inside your effect, which will make react execute the unsubscribe function whenever the hook is executed again and prevent you from having multiple active listeners. I suggest you read more about this topic here.
Upvotes: 1