简体   繁体   中英

Why firebase signInWithEmailAndPassword doesn't trigger onAuthChange?

I have the following function triggered when an user logs in:

const auth = firebase.auth();

export const signIn = ( email, password ) => (
    auth.signInWithEmailAndPassword( email, password )
    .catch(e => e ? console.log(e) : console.log(auth.currentUser))
);

If I type in incorrect details, the error is logged into the console, but if the details are correct, nothing happens.

When I check the network data in devtools, the request returns all the data it should, but inside the app, auth.currentUser is undefined (checked after log-in as well).

And as it's not too suprising,

export const getUser = () => (
    async dispatch => (
        auth.onAuthStateChanged(user => {
            const { uid } = user = {};
            console.log(user)
            if (uid) {
                console.log(uid)
                dispatch(
                    setUserId(
                        uid
                    )
                )
            } else {
                console.log("nologin")
            }
        })
    )
);

just gets triggered initially, when the app loads, with undefined and nologin . Inside the firebase console, authentication with email and password enabled, and the users are valid. I know it should work, as I made many authentication process through firebase, in the same way, so I can't provide more information, if you had the same problem, and you solved it, please let me know.

yes, I think this is related to the async nature of the Firebase design. So signInWithEmail... works, but it doesn't immediately reflect the change on the currentUser object. Instead, use the event onAuthStateChanged to do any code related to the currentUser. The process would be:

  1. Register the onAuthStateChanged event, and inside it detect for currentUser == null, this event will always get called on first definition with a null user, so by putting an if inside you can detect when you're dealing with an actual signIn.

  2. Add the signIn function, but don't do anything on the callback with the currentuser here, instead move the relevant code to onAuthStageChanged.

Also, not 100% sure that you have to wrap the event inside a module and export it, or that you should. When doing web apps, each page is supposed to be state-less and independent, so each page should have its own script code to check for auth events and do whatever is appropriate.

I do it like that and so far has worked all the time. Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM