0

I am having an axios intercept . It will catch every request . My idea is to dispatch errors commonly in the same place. So i created this intercept. If 404 error came means i will dispatch an action and redirect the page to home. But unfortunately i cant access the props.history in HOC.

Here i am sharing the code of what i have implemented:

HOC axios intercept:

import React, {useEffect} from "react";
import axios from "axios";

const checkRequests= Wrapped => {
    function CheckRequests(props) {
        useEffect(()=>{
            axios.interceptors.response.use(function (response) {
                // Do something with response data
                return response;
            }, function (error) {
                switch (error.response.status) {
                    case 404 :
                        props.history.push('/login') // will redirect user to login page 
                        break
                    default :
                        break
                }
                // Do something with response error
                return Promise.reject(error);
            });
        })

        return (
            <Wrapped {...props} />
        )
    }
    return CheckRequests
}

export default checkRequests

And wrapping this component in App.js:

import React from "react"
import CheckRequests from "./HOC/CheckRequests"

function App(props){ ... }

export default checkRequests(App)

Error:

When is console the props in HOC it comes empty

console.log(props) => {}

Please help me with that. Is there any other way to access the history.push from that HOC. For disptaching an action an action am using store.dispatch(logout()).

SDK
  • 1,356
  • 3
  • 19
  • 44
  • You can use `withRouter()`, check https://stackoverflow.com/questions/53539314/what-is-withrouter-for-in-react-router-dom/56622289#56622289 – rolory Mar 09 '20 at 12:45

3 Answers3

0

Wrap the withRouter HOC in the export statement like this:

export default withRouter(checkRequests);

Don't forget to import at the top of the file

import { withRouter } from "react-router";

joy08
  • 9,004
  • 8
  • 38
  • 73
0

You may use withRouter

import { withRouter } from 'react-router-dom';

export default withRouter(checkRequests);
Burak Gavas
  • 1,304
  • 1
  • 9
  • 11
0

Thanks for your answer. I added your suggestion into my code. But i got this error You should not use Route or withRouter() outside a Router . Then i found that it is outside the router so i added this

import { BrowserRouter } from 'react-router-dom';

ReactDOM.render(
   <BrowserRouter>
     <App />
   </BrowserRouter>

  , document.getElementById('root'));

on the index.js . It works fine.

SDK
  • 1,356
  • 3
  • 19
  • 44