Reputation: 23
I'm encountering an issue where my API responses are not updating unless I disable cache in the browser's DevTools. Here are the details:
Problem: When I make API calls using axios in my React application, the responses seem to be cached, and I do not receive the latest data. The only way to get the updated response is to disable the cache in the DevTools.
Current Implementation: Here is the helper function I'm using to send requests:
import { openNotificationWarning } from '@/components/Notification';
import { getAuthority, removeAuthority } from '@/utils/authority';
import axios from 'axios';
import { formatMessage } from 'umi';
axios.defaults.baseURL = process.env.API_URL;
function getCookie(value) {
const reg = new RegExp(`(^| )${value}=([^;]*)(;|$)`);
const arr = document.cookie.match(reg);
try {
if (arr) {
return unescape(arr[2]);
}
} catch (error) {
return null;
}
return null;
}
const instance = axios.create({
baseURL: process.env.API_URL,
timeout: 600000,
withCredentials: false,
});
instance.interceptors.request //REQUEST
.use(
async function (config) {
let authority = getAuthority();
var headers = { ...config.headers };
if (authority) {
headers['Authorization'] = `Bearer ${authority}`;
}
headers['X-Requested-With'] = 'XMLHttpRequest';
headers['Content-Type'] = 'application/json';
headers['X-XSRF-TOKEN'] = getCookie('XSRF-TOKEN');
config.headers = headers;
return config;
},
(error) => {
if (error && error.request) {
}
return Promise.reject(error);
},
);
instance.interceptors.response.use(
async function (response) {
if (response.status === 401) {
removeAuthority();
}
return {
response,
data: response.data,
};
},
(error) => {
if (error?.response?.status == 401) {
removeAuthority();
}
if (error?.response?.status == 403) {
openNotificationWarning(
'このサイトへアクセスは許可されていません。',
formatMessage({ id: 'pleaseCheckAgain' }),
'#f81d22',
);
}
if (error?.response?.data?.message == 'User is not logged in.') {
removeAuthority();
}
if (
error?.response?.data?.message ==
`Cannot read properties of undefined (reading 'access_token')`
) {
removeAuthority();
}
return { response: error, error: error.response };
},
);
const request = (url, options) => {
return instance.request({ ...options, url: url });
};
export default request;
Things I've Tried:
Disabling cache in browser DevTools (works, but not a practical solution for production).
I would appreciate any guidance on how to ensure that my API responses are not cached and always return the latest data.
Thanks a lot for your time and help!
Upvotes: 0
Views: 22