Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

350
Views
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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!