Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic handle 401 response with redux-saga and fetch

I'm building a "secured" application and using redux-saga together with fetchjs for doing the async calls to the backend.

My backend returns a 401 status code when the user is not authorized, i want to catch this "exception" globally and dispatch a action so my react application goes to the login screen.

I found the following solution: https://github.com/redux-saga/redux-saga/issues/110, but in this case the handling for the 401 should be explicit in every saga that we build.

By adding code to every saga it becomes more complex. It also increases the chances a developer forgets to add the code for handling the 401 code.

Is there a nice way to handle this 401 response globally?

like image 580
Lrdv Avatar asked Jan 22 '17 18:01

Lrdv


People also ask

How does Redux handle data fetch?

Data fetching logic for Redux typically follows a predictable pattern: A "start" action is dispatched before the request, to indicate that the request is in progress. This may be used to track loading state to allow skipping duplicate requests or show loading indicators in the UI.

Should I put all loading logic in Redux?

NOTE: don’t put all loading logic into redux blindly, only if the data you are fetching is stored into redux , then the loading logic should be handled in redux-saga,thunk etc. If the data is stored in component state, then the loading flags should also be stored in component state. One example is an autocomplete search component.

How do I write async logic with Redux toolkit?

Redux Toolkit's configureStore function automatically sets up the thunk middleware by default, and we recommend using thunks as the standard approach for writing async logic with Redux. Earlier, we saw what the synchronous data flow for Redux looks like.

Why do we use thunk functions in Redux?

The thunk functions can have any async logic we want inside, and that logic can dispatch actions and read the store state as needed. Writing async logic as thunk functions allows us to reuse that logic without knowing what Redux store we're using ahead of time.


1 Answers

I would not use redux-saga since it does not have ability to do what you require.

Instead, when setting up store, API layer and other things configure API layer do invoke handler on every error occurred.

Sample of API layer that reports invokes error handler.

const conf = {
    onError: () => {},
}

api.onError = (cb) => {
    conf.onError = cb;
}

api.get = (url) => {
    fetch(url)
        .then(response => {
            if (response.ok === false) {
                return conf.onError(response);
            }
            return response;
        })
        // Network error
        .catch(conf.onError)
}

Configure application.

import store from './store';

// Configure your API wrapper and set error callback which will be called on every API error.
api.onError((error) => {
    store.dispatch({
        type: 'API_ERROR',
        payload: error,
    });
});

// In you reducers...
isAuthorized(state, action) {
    if (action.type === 'API_ERROR' && action.payload.statusCode === 401) {
        return false;
    }
    return state;
}

Then, call API as usually, If error occurs, action is dispatched to store and you may or may not react to this actions.

like image 155
Andreyco Avatar answered Nov 15 '22 05:11

Andreyco