I am looking for a good way to use the history object of react-router-dom
anywhere in the app. No matter it's a react component or not.
The solution I thought might be good was using the window
object.
in App.jsx
import React from "react";
import { useHistory } from "react-router-dom";
import { getUser } from "./axios";
const App = () => {
let history = useHistory();
if (!window.reactHistory) {
window.reactHistory = history;
// attach history object to window object.
}
React.useEffect(() => {
getUser();
}, []);
return (
<div className="App">
</div>
);
};
export default App;
in Index.js nothing too fancy,
import { StrictMode } from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { BrowserRouter as Router } from "react-router-dom";
const rootElement = document.getElementById("root");
ReactDOM.render(
<StrictMode>
<Router>
<App />
</Router>
</StrictMode>,
rootElement
);
In api.js
import axios from "axios";
export const getUser = async () => {
try {
const res = await axios.get("");
if (res.status === 401) {
if (window.reactHistory) {
console.log("reactHistory :", window.reactHistory);
window.reactHistory.push("/login");
// access react-router-dom history via window object
}
}
} catch (err) {}
};
Used react-router-dom version is 5.3.0
.
You can find the code above in my codesandbox. https://codesandbox.io/s/goofy-yonath-o13kcq?file=/src/App.js
I tested this approach and it's worked well so far. But no one seems to use the history object this way and I wondered whether it's a really good way.
I'd appreciate it if you give your opinion. Thanks!