Open Arsh1a opened 1 year ago
react-query has their own way of getting a 401 refresh token - use that.
For people that are running into this problem nowadays, there is a straight forward solution.
Promise.reject(failedRequest)
in order for react query to get this.createAuthRefreshInterceptor
'catches' the subsequent failed request.You'll want two axios clients. One that is wrapped in the createAuthRefreshInterceptor
, and one that is not. Here is what we're using in our project.
export class AxiosHttpRequestWithRetry extends BaseHttpRequest {
private refreshableAxiosInstance = axios.create();
private refresherAxiosInstance = axios.create();
private refreshAuthLogic = (failedRequest: any) => {
const refreshUrl = this.config.BASE + '/jwt/refresh/';
const refreshToken = getRefreshToken();
if (!refreshToken) {
return Promise.reject(failedRequest);
}
const result = this.refresherAxiosInstance // Notice this is the unwrapped client.
.post(refreshUrl, {
refresh: refreshToken,
})
.then((tokenRefreshResponse) => {
localStorage.setItem('access', tokenRefreshResponse.data.access);
failedRequest.response.config.headers['Authorization'] =
'Bearer ' + tokenRefreshResponse.data.access;
return Promise.resolve();
}).catch((error) => {
localStorage.removeItem('access');
localStorage.removeItem('refresh');
queryClient.invalidateQueries(['user']); // You'll probably want to invalidate your query that fetches user info
return Promise.reject(failedRequest); // This causes react query to enter the failed state
});
return result;
};
constructor(config: OpenAPIConfig) {
super(config);
createAuthRefreshInterceptor(this.refreshableAxiosInstance, this.refreshAuthLogic);
}
public override request<T>(options: ApiRequestOptions): CancelablePromise<T> {
return __request(this.config, options, this.refreshableAxiosInstance);
}
}
So if the Function that calls the refresh authorization fails, React-query isLoading will always be true.
Here is my code:
And this is how i use it using react-query
If I console log
isLoading
, it will be always true even thoisError
is true, so the`isLoading
`should be false.