Automatic handle 401 response with redux-saga and fetch
Asked Answered
A

1

8

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?

Allsun answered 22/1, 2017 at 18:2 Comment(0)
D
6

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.

Drawn answered 22/1, 2017 at 18:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.