I have an api configuration which handles all the api calls in the app. When the token expires, the backend gives a 403 status and based on that i need to update the tokens. Here is the code i have:
// General api to access data
import ApiConstants from './ApiConstants';
import {store} from '../redux/store';
import * as loginActions from '@/redux/actions/loginActions';
export default function api(path, params, method, extraHeaders) {
let options = {
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
device: 'mobile',
Authorization: 'Bearer ' + store.getState()?.authReducer?.token,
...extraHeaders,
// ...(token && {token: token}),
},
method: method,
...(params && {body: JSON.stringify(params)}),
};
return fetch(ApiConstants.BASE_URL + path, options)
.then(response => {
return new Promise(function (resolve, reject) {
response.json().then(responseParsed => {
if (response.status == 200 || response.status == 201 || response.status == 204) {
// success
resolve(responseParsed);
} else if (response.status == 403) {
// access token unauthorised
if (store.getState()?.authReducer?.token) {
toast.show('Session Expired. Please Login again', {
type: 'danger',
position: 'bottom',
duration: 3000,
offset: 30,
animationType: 'zoom-in',
});
}
store.dispatch(loginActions.logOut());
resolve({status: false, result: responseParsed});
} else {
toast.show(responseParsed?.message, {
type: 'danger',
position: 'bottom',
duration: 3000,
offset: 30,
animationType: 'zoom-in',
});
resolve({status: false, result: responseParsed}); // failed
}
});
});
})
.catch(err => {
// alert('yay')
console.log('error at utility in function apiCall at catch: ' + err);
// showSnackbar('Something went wrong, please check your network.');
// Snackbar.show({ text: "Something went wrong", duration: Snackbar.LENGTH_LONG });
});
}
How to intercept the call and add the refresh the token logic in this flow?