Home > Software engineering >  how to catch error in redux action and display the error message in UI
how to catch error in redux action and display the error message in UI

Time:07-09

I have a redux action called academyRedirect.js which is invoked whenever an user is redirected to the path /user/academy when he pushes the 'academy' button in my main page.

    export const getAcademyAutoLogin = () => {
  axios.get(`/user/academy`)
    .then((response) => {
      window.location.replace(response.data); // this is replaced by an URL coming from backend
    })
    .catch((error) => {
      reject(error.response);
    });
    return null;
};

Whenever the user is not allowed to access the academy (for not having credentials) or whenever i get an error 500 or 404, i need to display a modal or something to inform the user that an error occurred while trying to log into the academy. Right now im not being able to do it, the page just stays blank and the console output is the error.response. Any help is appreciated

CodePudding user response:

Redux Store

export const messageSlice = createSlice({
    name: 'message',
    initialState: { isDisplayed: false, errorMessage: ''},
    reducers: {
        displayError(state, action) {
            state.isDisplayed = true
            state.errorMessage = action.message
        },
        resetErrorState() {
            state.isDisplayed = false
            state.errorMessage = ''
        },
    }

})

export const messageActions = messageSlice.actions;

Inside the component:-

const Login = () => {
    const errorState = useSelector(globalState => globalState.message)
    
    const onClickHandler = async => {
         axios.get(`/user/academy`)
         .then((response) => { window.location.replace(response.data) })
         .catch((error) => {
         dispatch(messageActions.displayError(error))
    });
    }
    
    return (
        {errorState.isDisplayed && <div>{errorState.errorMessage}</div>}
        {!errorState.isDisplayed &&<button onClick={onClickHandler}>Fetch Data </button>}
    )

}

Maybe this is of help to you

CodePudding user response:

You can try to add interceptor to your axios.

Find a place where you create your axios instance and apply an interceptor to it like this

const instance = axios.create({
  baseURL: *YOUR API URL*,
  headers: { "Content-Type": "application/json" },
});


instance.interceptors.request.use(requestResolveInterceptor, requestRejectInterceptor);

And then, in your requestRejectInterceptor you can configure default behavior for the case when you get an error from your request. You can show user an error using toast for example, or call an action to add your error to redux.

For second case, when you want to put your error to redux, its better to use some tools that created to make async calls to api and work with redux, for example it can be redux-saga, redux-thunk, redux-axios-middleware etc.

With their docs you would be able to configure your app and handle all cases easily.

  • Related