Christian Tchaikovsky
Christian Tchaikovsky

Reputation: 192

React router v6 how to use `navigate`. Axios interceptors

React router v6 how to use navigate. Axios interceptors

There are many examples on the Internet. But how to do it right? If possible, please provide a detailed description. Thanks!

import axios from 'axios'

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) {
        //navigate('/login')
    }
    return Promise.reject(error)
})

Upvotes: 3

Views: 4069

Answers (1)

Damian Busz
Damian Busz

Reputation: 1848

You can pass navigate down the interceptor if you will wrap it in a functional component and initialize it inside your app.js

First, lets create a function that will work as our interceptor Promise, its supposed to take navigate as its param

const AxiosInterceptorsSetup = navigate => {
    HTTP.interceptors.response.use(
        response => response,
        error => {
            if (error.response.status === 401) {
                navigate('/login');
            }
            return Promise.reject(error);
        }
    );
};

export default AxiosInterceptorsSetup;

Now we need to create functional component inside app.js that will use our AxiosInterceptorsSetup

function AxiosInterceptorNavigate() {
    let navigate = useNavigate();
    AxiosInterceptorsSetup(navigate);
    return <></>;
}


function App(props) {
   return (
       <BrowserRouter>
           {<AxiosInterceptorNavigate />}
            {...}
           </Routes>
       </BrowserRouter>
   );
}

Upvotes: 5

Related Questions