1
function reducer(state = initialState, action) {
    //const [success,setSuccess] = useState(false)  :This is giving me an error:
    let success = false; //want to access this variable 
    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
            success=true //from this line
        }).catch((e) => {

        })
    }
    if(success){
      //do something.....
    }

I want to access the success variable from within that arrow function defined. How can i do that?

Edit: On reaching if statement there is no change in the value of success. But the flow is going inside that arrow function

abhi_awake
  • 186
  • 1
  • 8

1 Answers1

1

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_USERaction, you should first log the user in and then dispatch an action containing the information of the logged in user.

Linschlager
  • 1,539
  • 11
  • 18