Search code examples
reactjsreduxredux-saga

redux and redux-saga : Reducer returns a promise instead of a regular object


Just like the title says, my reducer returns a promise instead of a regular object. I am assuming this is because I am using redux-saga for async requests, which kinda does not make sense. Is there a way to have my reducer return a resolved object instead?

// reducer.tsx
...
const initialState = {
  token: '',
  error: null,
  loading: false
};

const authenticationReducer = async (state = initialState, action) => {
  switch (action.type) {
    case EMAIL_LOGIN: {
      console.log('action.payload: ', action.payload);
      const {token} = action.payload;

      return {
        ...state,
        token
      };
    }

...
// saga.tsx

function* emailLogin({type, payload}) {
  try {
    const {email, password} = payload;

    const loginUserInfo = {
      email,
      password,
    };

    const response = yield call(axios, `${USER_ADDRESS}/login/`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: loginUserInfo,
    });

    yield put(setLoginStatus(response));
  } catch (e) {}
}

But for some reason both useSelector() and useStore() indicates that my reducer returns a promise

//  Login.tsx

...
const token = useSelector(state =>{ console.log(state)}) // {authentication: Promise}
const state = useStore().getState();
console.log(state)   // {authenitcation: Promise}
...

Please help!


Solution

  • async functions always return a promise. Redux reducers must never be async!

    In this case, all you should need to do is remove the async keyword from the reducer.