When user changed language i’m sending selected language in Accept-Language field on header of the request via axios, then i’m fetching data with UseQuery using this axios interceptor, but new data is being fetched only when user makes new request , i want it to be made instantly when language is changed.
This is my language store;
const initialState = {
language: 'ru',
}
export const useLanguageStore = create(
persist(
(set) => ({
...initialState,
setLanguage: (language) => set({ language }),
}),
{
name: 'language_storage',
version: VERSION.V1,
}
)
);
API REQUEST function
const history = createBrowserHistory();
const apiRequest = axios.create({
baseURL: BASE_URL,
headers: {},
params: {},
});
apiRequest.interceptors.request.use((config) => {
const token = Cookies.get(TOKEN.AUTH_TOKEN);
const {language} = useLanguageStore.getState();
if (token) {
config.headers['authorization'] = `Bearer ${token}`;
config.headers['Accept-Language'] = language;
}
return config;
});
apiRequest.interceptors.response.use((response) => {
return response.data;
}, (err) => {
if (err?.response?.status === 401) {
useAuthStore.setState({ authed: false });
history.push('/');
notifications.show({
title: 'Error',
message: 'You are not authorized to access this page',
color: 'red'
})
Cookies.remove(TOKEN.AUTH_TOKEN);
location.reload();
} else if (err.message === 'Network Error') {
console.log('Network Error');
} else {
console.log('Network error 2');
}
return Promise.reject(err);
});
Here’s how i used useQuery hook (i have many queries regarding the pages), i don’t think that it is good solution to add language dependancy to each of them listen to lang change, is there any other solution to handle it automatically on the root of the react query
const fetchCategoryList = async (queryParams) => {
return await apiRequest.get(`${API_KEYS.CATEGORY_LIST}?${queryParams}`).then(res => res.data);
};
export const useCategoryList = ({ orderby = 'id', parent_id, sort = 'asc', per_page = 10, page = 1, id, search }) => {
const queryParams = new URLSearchParams({
orderby,
sort,
per_page,
page,
...(parent_id && { parent_id }),
...(id && { id }),
...(search && { search }),
}).toString();
return useQuery(
['category-list', { orderby, parent_id, sort, per_page, page, id, search }],
() => fetchCategoryList(queryParams),
{
keepPreviousData: true,
refetchOnWindowFocus: false,
}
);
};
Oybek Ikramov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.