How to access a story object outside of a reactive component

First of all, I am well acquainted with withRouter HoC, however in this case it does not help, because I do not want to access the object historyin the component.

I am trying to create a mechanism that redirects the user to the login page if I return 401 from the API endpoint. I use axios to create http requests . I have about 60 endpoints that I need to cover, which are used in a dozen components throughout the application.

I want to create a decorator function for an instance instance of axios, which:

1. makes the request
2. if fail && error_code = 401, update user route to `/login`
3. if success, return promise

The problem with the above is updating the user’s route. I used to react-router-v3be able to import an object browserHistorydirectly from the response-router package, which is no longer possible.

So my question is: how can I access the history object outside of the React component without passing it through the call stack?

+4
source share
1 answer

response-router v4 also provides a way to share history through a package history, namely a function createBrowserHistory().

The important part is to make sure that the same story object is used in your application. You can take advantage of the fact that node modules are single.

history.js :

import createBrowserHistory from 'history/createBrowserHistory';

const history = createBrowserHistory();
export default history;

:

import history from "./history.js";

, Router history prop (BrowserRouter does not), JSX :

import { Router } from "react-router-dom";
import history from "./history.js";

// and then in your JSX:
return (
  <Router history={history}>
    {/* routes as usuall */}
  </Router>
)

https://codesandbox.io/s/owQ8Wrk3

+6

Source: https://habr.com/ru/post/1677832/


All Articles