I am using Axios in a React Project and to make some common code for errors I wanted to create Axios Instance and use interceptors.
Following is my code for my React Routes
import React, { Component } from "react";
import { Route, Switch } from "react-router-dom";
import Home from "./scenes/Home";
import { ProtectedRoute } from "./_hoc/ProtectedRoute";
import Admin from "./scenes/Admin";
import Login from "./components/Auth/Login";
export default class Routes extends Component<any, any> {
render() {
return (
<div>
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/login" component={Login} />
<ProtectedRoute exact path="/admin" component={Admin} />
</Switch>
</div>
);
}
}
Following is the code for my Axios Instance
import axios from "axios";
const axiosInstance = axios.create({
baseURL: `http://localhost:55266/api/`
});
axiosInstance.interceptors.request.use(request => {
if (request.url != "/Login/Authenticate") {
//TO DO
//request.headers["Authorization"] = "Bearer";
}
return request;
});
axiosInstance.interceptors.response.use(
response => {
if (
response.request.responseURL ==
response.config.baseURL + "Login/Authenticate"
) {
localStorage.setItem("TAGAuthToken", response.data.data.token);
//I DON'T WANT THIS PAGE TO GET RELOADED.
window.location.href = "/Admin";
}
return response;
},
error => {
return Promise.reject({ ...error });
}
);
export default axiosInstance;
I don't want to reload the page via using window.location but want to navigate via history. I am not able to get the clue how to achieve that.
The way I see in various tutorials are they say to use Router instead of Switch and use the history v4 library and then we can use history anywhere, but I would like to stick with Switch instead of Router.
Looking forward to valuable responses.
NOTE: I have already checked the post Programmatically navigate using react router but that doesn't answer my question. I want to navigate from the AxiosInstance File. It can be achieved via History NPM package but requires to use Router but as per my requirement I need to use Switch