Currently, I have this Axios call, what I want to achieve is use interceptors inside ES6 generators.
I want to use axios interceptors to retry a request if the back end service sends back a "401" response, any suggestion?
const token = '...';
export function* getUsers(user) {
return yield axios({
headers: {
Accept: "Aplication/json",
Authorization: `Bearer ${token}`,
},
method: "get",
url: '/getUsers/:id'
})
.then(data => data)
.catch(e => e)
}
May be you can try something like this.
import axios from "axios";
export const getClient = (token) => {
const options = {};
if (token !== null) {
options.headers = { Authorization: `Bearer ${token}` };
}
const instance = axios.create(options);
instance.interceptors.response.use((response) => response, (error) => {
if (error.response.status === 401) {
window.location = '/logout'; // Or whatever you want to do
}
return Promise.reject(error);
});
return instance;
};
export function* getUsers(user) {
return yield getClient('JTW_TOKEN').get('/getUsers/:id').then(data => data).catch(e => e)
}
Personally I prefer to have separate method for get/post/delete/put/patch etc but its not must by any means.