I am working on a React application that uses redux-saga
.
I am a bit stuck on this so I am reaching out for some help/guidance.
I am trying to implement a global error handler, the goal is that every time the api sends back a 500
user should be redirected to a 500 page.
I thought a good way to do this was to use axios interceptors
This is my interceptor (skimmed down, to bare minimum):
import axios from 'axios';
import history from '../components/history'; // this is trouble
export default {
configureAxios: (store) => {
// Add a response interceptor
axios.interceptors.response.use((response) => {
// will work on this later
return response;
}, (error) => {
// catches if the session ended!
return Promise.reject(error);
});
axios.interceptors.response.use(undefined, (error) => {
// still very much work in progress
if (error.response.status >= 500) {
// maybe fire off an action to update the store
history.push('/500');
}
return Promise.reject(error);
});
}
};
Is this a good approach?
If it is, I have a problem where history.push
does update the url but doesn't redirect to the page. I looked at this answer but couldn't get it to work.
Since it's using react-router-dom
v4 I though to follow what is suggested here
Installed history with npm i history --save
I created my history.js
import { createBrowserHistory } from 'history';
export default createBrowserHistory();
and then in root.js
import history from './history';
//some stuff here
const App = ({ matchedRoutes }) =>
<div>
<Head />
<Header />
<Switch>
{matchedRoutes.map((route, i) =>
<RouteWithSubRoutes key={i} {...route} />
)}
</Switch>
<Main />
</div>;
const Root = ({ store }) => (
<Provider store={store}>
<Router history={history}>
<App matchedRoutes={routes} />
</Router>
</Provider>
);
Any idea what I am doing wrong? any suggestion on how to better implement this?