We can use useNavigate from React Router v6 inside Axios interceptors by creating a custom hook or using a wrapper function. Since React hooks like useNavigate can only be used inside components or hooks, we need a workaround to access it inside an Axios interceptor. By creating a Navigation Helper, we can store the navigate function and use it inside Axios interceptors efficiently.

Using a Navigation Helper

We can create a separate module to manage navigation outside of React components.

1: Create a Navigation Helper

Create a file (navigateHelper.js) to store the navigate function:

// navigateHelper.js
let navigateFunction;
export const setNavigate = (navigate) => {
    navigateFunction = navigate;
};
export const navigateTo = (path) => {
    if (navigateFunction) {
        navigateFunction(path);
    }
};

2: Modify Axios Interceptor

Use this helper in our Axios interceptor:

import axios from "axios";
import { navigateTo } from "./navigateHelper";
export const HTTP = axios.create({
    baseURL: "http://URL.ru/",
    headers: {
        "content-type": "application/json",
    },
});
HTTP.interceptors.response.use(
    response => response,
    error => {
        if (error.response?.status === 401) {
            navigateTo("/login");
        }
        return Promise.reject(error);
    }
);

3: Initialize Navigation in App Component

Set up the navigate function inside our App.js:

import { BrowserRouter as Router, Routes, Route, useNavigate } from "react-router-dom";
import { setNavigate } from "./navigateHelper";
import Home from "./Home";
import Login from "./Login";
const AppWrapper = () => {
    const navigate = useNavigate();
    setNavigate(navigate); // Set navigate function globally

    return (
        
            } />
            } />
        
    );
};
const App = () => (
    
        
    
);
export default App;

Need Help With React Development?

Work with our skilled React developers to accelerate your project and boost its performance.

Hire Reactjs Developers

Support On Demand!

Related Q&A