I am new to firebase. I'm trying to login using React + Redux. When I click 'Login', it will log me in once, then the onAuthStateChanged is called again with res being null which logs me back out
Here's my Firebase service:
const initFirebase = () => {
firebase.initializeApp(config.firebase)
firebase.auth().onAuthStateChanged((res) => {
console.log('Firebase - onAuthStateChanged', {res})
if(res) {
const formData = {
email: res.email,
uid: res.uid,
}
// Check if email exists against local API
APIAuthService(endpoint, 'post', formData).then(response => {
if(response.status) {
let userData = response.data
store.dispatch(authAction.login(userData))
}
})
}
else {
store.dispatch(authAction.logout())
}
})
}
Also my Login.js component can viewed here (Line:41) https://pastebin.com/qcRH6gv2
If someone is looking for a way to simply listen to the state changed only once then just assign the onAuthStateChanged to a variable, that will be the unsubscribed function and simply call it. So for example something like this:
const unsubscribe = onAuthStateChanged(auth, (user) => {
unsubscribe();
// Do something with the user...
console.log('firebase user:', user);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With