Search code examples
reduxredux-thunk

Why is the result of my Redux Thunk action return a Promise?


After I enter the user's correct email and password the reducer returns SIGNED_IN value wrapped within a Promise. I am confused as to why does it not return simply 'SIGNED_IN':true?

authentication: Promise
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: Object
SIGNED_IN: true

I am dispatching this action:

const mapDispatchToProps = dispatch => ({
  authUser: () => dispatch(authUser('[email protected]', 'xzy98765'))
})

Action creator:

export const authUser = (email, password) => async dispatch => {
  console.log('asd')
  try {
    const user = await Auth.signIn(email, password)
    if (user.challengeName === 'MFA_SETUP') {
        // This happens when the MFA method is TOTP
        // The user needs to setup the TOTP before using it
        // More info please check the Enabling MFA part
        //Auth.setupTOTP(user);
    } else {
        // The user directly signs in
        console.log(user)
        return dispatch({type:'SIGN_IN_USER_SUCCESS'})
    } 
  } catch (e) {
    console.log(e)
    return dispatch({type:'SIGN_IN_USER_FAIL'})
  }
}

Reducer:

export default async (state, action) => {
  console.log('authReducer state',state)
 switch (action.type) {
  case 'SIGN_IN_USER_SUCCESS':
    return {
      ...state,
      SIGNED_IN: true
    }
  case 'SIGN_IN_USER_FAIL':
    return {
      ...state,
      SIGNED_IN: false
    }
  }
}

Solution

  • Your reducer shouldn't be async (async functions always return a promise). Just do it like this:

    export default function (state, action)
    

    It's your actions that are async because they are awaiting response, the reducer is just a normal function which accepts the values from the async actions.