The problem here is not that the variable is not updated but rather that it is updated after you expect it to be. This happens because fire.auth().signInWithEmailAndPassword(action.payload.username, action.payload.pass)
returns a promise and therefore works asynchronously.
You can solve your issue in two main ways:
Async/Await
To work around that, you could leverage the new async
/await
syntax for handling asynchronous code (Check for browser support here). This would look something like this:
// ...
if (action.type === LOG_USER) {
const res = await fire.auth().signInWithEmailAndPassword(action.payload.username, action.payload.pass);
console.log("entered"); //this output is showing in the console
success = true; //from this line
}
// ...
Move the success handler
Another, more widely supported approach is to move the success handler into the promise callback like so:
// let success = false; // This is no longer needed
if (action.type === LOG_USER) {
fire.auth().signInWithEmailAndPassword(action.payload.username, action.payload.pass).then((res) => {
console.log("entered") //this output is showing in the console
// Handle success here
}).catch((e) => {
})
}
That being said, you shouldn't dispatch requests from reducers. As you can read here (while this article talks about redux-reducers, it's also the case for useReducer-reducers), a reducer is supposed to be a pure function, meaning it transforms some input into some output, without any side effects. This means, a reducer function, given the same previous state and the same action should always return the same result.
So instead of listening to the LOG_USER
action, you should first log the user in and then dispatch an action containing the information of the logged in user.