Skip to content

Instantly share code, notes, and snippets.

@cdaz5
Last active February 12, 2019 22:42
Show Gist options
  • Save cdaz5/b9dd9914063f090e527fbb7708fcb097 to your computer and use it in GitHub Desktop.
Save cdaz5/b9dd9914063f090e527fbb7708fcb097 to your computer and use it in GitHub Desktop.
httpInterceptors
import axios from 'axios';
import { authOperations } from 'where you keep your actions/operations';
// whats a tutorial without an obscure authService :)
import authService from './authService';
const httpService = {
// we pass the redux store and history in order to dispatch the logout actions
// and push the user to login
setupInterceptors: (store, history) => {
axios.interceptors.response.use((response) => {
// simply return the response if there is no error
return response;
}, (error) => {
// in this case we only care about unauthorized errors
if (error.response.status === 401) {
// we dispatch our logout action (more than likely changes a boolean
// somewhere in your store ex. isAuthenticated: false)
store.dispatch(authOperations.logoutSuccess());
// this could just as easily be localStorage.removeItem('your-token')
// but it's best to encapsulate this logic so it can be used elsewhere
// by just importing it.
authService.removeToken();
// send the user to the login page since the user/token is not valid
history.push('/login');
}
return Promise.reject(error);
});
}
};
export default httpService;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment