1

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

Manoj Sethi
  • 1,898
  • 8
  • 26
  • 56
  • Possible duplicate of [Programmatically navigate using react router](https://stackoverflow.com/questions/31079081/programmatically-navigate-using-react-router) – James May 05 '19 at 17:47
  • @James : I want to handle the navigation from axios interceptor. The solution talks about the components and the other solution https://stackoverflow.com/a/36102045/2159510 asks to use Router instead of Switch. – Manoj Sethi May 05 '19 at 17:51

0 Answers0