简体   繁体   中英

redux to redux-toolkit refactoring

can somebody explain why this code dispatching 'actions.loginSuccess' when i get 401 error from server? isn't it should go to 'catch' part of axios request?

Before i did it without redux toolkit features

const login = ({username, password}) => async dispatch => {
  await axios.post(`${API_URL}/token/`, {username, password})
    .then(response => {
      dispatch(actions.loginSuccess({ client_id: response?.data.client_id }))
      history.push('/')
    })
    .catch(e => {
      dispatch(actions.loginError({ error: String(e) }))
    })
} 

//actions.js
const login = createAction('@USER/login')
const loginSuccess = createAction('@USER/login-success')
const loginError = createAction('@USER/login-error')

export const actions = {
  login,
  loginSuccess,
  loginError
}

//reducers.js

export const userReducer = createReducer(initialState, builder => {
  builder.addCase(actions.login, draft => {
    draft.loading = true
  })
  
  builder.addCase(actions.loginSuccess, (draft, action) => {
    draft.loading = false
    draft.isLoggedIn = true
    draft.data = { ...draft.data, client_id : action.client_id}
  })
  
  builder.addCase(actions.loginError, (draft, action) => {
    draft.loading = false
    draft.error = action.payload.error
    draft.isLoggedIn = false
    draft.isSignedup = false
  })
}

can somebody explain why this code dispatching 'actions.loginSuccess' when i get 401 error from server? isn't it should go to 'catch' part of axios request?

 // there's a difference beetween HTTP Status Code and Server Response Body Code.

 // if HTTP status code is not 200, it should dispatched loginError()

 // if HTTP status code is 200, and theres a response body JSON

 // e.g 
 const resp = {
   statusCode: 401,
   message: 'unauthorized',
 }

 // You must make if conditions to handle that error code

Here's redux-toolkit version of your code to handle either HTTP status code 401, or body response code

// import axios & history
import { createSlice } from '@reduxjs/toolkit';

const initialState = {
  data: {},
  loading: false,
  isLoggedIn: false,
  isSignedup: false,
};

// Reducers
const userSlice = createSlice({
  name: '@USER',
  initialState: initialState,
  reducers: {
    loginStart(state) {
      state.loading = true;
    },
    loginSuccess(state, action) {
      state.data = { 
        ...state.data, 
        client_id: action.payload.client_id 
      };
      state.loading = false;
      state.isLoggedIn = true;
    },
    loginError(state, action) {
      state.loading = false;
      state.error = action.payload.error;
      state.isLoggedIn = false;
      state.isSignedup = false;
    },
  },
});

// actions
export const { loginStart, loginSuccess, loginError } = userSlice.actions;
export default userSlice.reducer;

export const login = ({ username, password }) => async (dispatch) => {
  dispatch(loginStart());
  try {
    const response = await axios.post(`${API_URL}/token/`, {
      username,
      password,
    });
    if(response && response.statusCode !== 200){
      return dispatch(loginError({ error: response.message }));
    }

    dispatch(loginSuccess({ client_id: response?.data.client_id }));
    history.push('/');
  } catch (e) {
    dispatch(loginError({ error: String(e) }));
  }
};

don't forget to add userSlice into configureStore()

const reducer = {
  "@USER": userReducers, //got from export default userSlice.reducer
};

export default configureStore({
  reducer,
  middleware,
  devTools: process.env.NODE_ENV !== 'production',
});

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