Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

axios interceptor navigate (use history) with react-router-dom v6.3.0 and unstable_HistoryRouter

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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';
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading