javascriptreactjsaxiosinterceptorreact-hoc

React: axios.interceptors do not work in hoc


axios.interceptors in hoc withErrorHandler work for clicked method in App.js, but do not work for componentWillMount or componentDidMount in App.js. How can I fix it?

App.js

class App extends Component {
  componentDidMount() {
    axios.get('https://wrongaddress')
        .then(response => {
          console.log(response);
        });
  }

  clicked() {
      axios.get('https://wrongaddress')
          .then(response => {
              console.log(response);
          });
  }

  render() {
    return (
        <button onClick={this.clicked}>btn</button>
    );
  }
}
export default withErrorHandler(App, axios);

hoc/withErrorHandler.js

const withErrorHandler = ( WrappedComponent, axios ) => {
    return class extends Component {
        componentDidMount() {
            axios.interceptors.request.use(req => {
                console.log(req);
                return req;
            });
        }

        render() {
            return (
                <WrappedComponent {...this.props} />
            );
        }
    }
};

Solution

  • You add the interceptor in the hoc just after the first render. And you use axios in componentWillMount in the App. componentWillMount is before the first render.

    I suggest to place the axios call to componentDidMount in the App. It is recommended to put all side effects like load data to componentDidMount anyway. Check the documentation here: https://reactjs.org/docs/react-component.html#componentdidmount

    class App extends Component {
      componentdidMount() {
        axios.get('https://wrongaddress')
            .then(response => {
              console.log(response);
            });
      }
    
    ...
    

    Also you can move the interceptor handling in the HOC to componentWillMount.

    const withErrorHandler = ( WrappedComponent, axios ) => {
        return class extends Component {
            componentWillMount() {
                axios.interceptors.request.use(req => {
                    console.log(req);
                    return req;
                });
            }