I have interceptor which basically if error doing post request for new access and refresh token, but if new refresh token is no longer valid i need to redirect automatically to ("/"). Prefer to use useNavigate
But useNavigate could be used only inside react component.
I start googled and found that in react-router-dom from 6 version maintain global history and it has access anywhere.
I tried to history push("/") but it has no affect and i have no idea why it doesn’t work. What i’m missing?
App.tsx
export let history = createBrowserHistory();
const queryClient = new QueryClient();
function App() {
return (
<QueryClientProvider client={queryClient}>
<HistoryRouter history={history}>
<Views />
</HistoryRouter>
</QueryClientProvider>
);
}
export default App;
interceptors(axios_instance.js):
import history from './App'
const refreshAccessToken = async (navigate) => {
try{
const res = await axiosInstanceRefresh.post(
`${baseUrl}auth/refresh`,
null,
{headers: {'Authorization':`Bearer ${localStorage.getItem('refreshToken')}`}}
)
}catch{
console.log('NEED TO USE RELOGIN') // works
localStorage.removeItem('accessToken') // works
localStorage.removeItem('refreshToken') // works
history.push('/'); // Doesn't work
}
return await res.json()
}
axiosInstance.interceptors.request.use(async request => {
request.headers.Authorization = `Bearer ${localStorage.getItem('accessToken')}`;
return request;
}, function (error) {
return Promise.reject(error);
});
axiosInstance.interceptors.response.use(function (response) {
return response;
}, async function (error) {
const originalRequest = error.config;
if (error.response.status === 401) {
const access_token = await refreshAccessToken();
return axiosInstance(originalRequest);
}
return Promise.reject(error)
});
export default axiosInstance
>Solution :
import history from './App' is the App component, not the history object. I think you meant to import the named history export from ./App.
Example:
import { history } from './App';