Firebase.auth().onauthstatechanged Looping Infinitely
I have this code: function App() { const { setUser } = useContext(UserContext); firebase.auth().onAuthStateChanged((user) => { console.log('test'); if (user) {
Solution 1:
This can be the responsibility of your Provider itself and run inside it's useEffect
like so :-
exportfunctionUserContextProvider({ children }: IUserContextProvider) {
const [user, setUser] = useState<IUser | null>(initialState);
useEffect(()=>{
const unsubscribe = firebase.auth().onAuthStateChanged((user) => {
console.log("test");
if (user) {
console.log("user");
setUser({ id: user.uid, email: "" });
} else {
console.log("null");
setUser(null);
}
});
return unsubscribe;
},[])
return (
<UserContext.Providervalue={{user, setUser }}>
{children}
</UserContext.Provider>
);
}
The onAuthStateChanged
only needs to be registered one-time and so []
dependency array useEffect
is the right place for it. The unsubscribe
will only work when this component unmounts which won't happen for you unless you exit the website.
Post a Comment for "Firebase.auth().onauthstatechanged Looping Infinitely"