0

I want to show/call a custom react error component. Below is my code snippet. I am getting error since my axios interceptor is neither a react component nor a custom Hook.

    axios.interceptors.response.use((response) => {
if (response.config.parse) {
    //perform the manipulation here and change the response object
}
 return response;
}, (error) => {
//Want to call the component here
return Promise.reject(error.message);
});
Gurpinder
  • 634
  • 1
  • 5
  • 18

1 Answers1

-1

I don't think you can render a component in an axios interceptor.

The interceptor will intercept every response you make, and if there is an error do something with the error.

Meaning React would have no way of knowing what to render in which part of the DOM based on an error on any response from axios. Here is a good explanation of how interceptors work and good use cases for them

If you want to render an error message to the user then don't intercept the response. Just wait until the response errors (in a normal request not an interceptor) then pass that error to your own error component.

In practice that might look something like the below

function apiQuery (url) {
const [error, setError] = useState(null);
const [api, setApi] = useState(null);

axios.get(url)
  .then(function (response) {
    // handle success
    setApi(response.data)
  })
  .catch(function (error) {
    // handle error
    setError(error)
  })

return { api, error }
}

Now you have access to the error response which you can pass into your own error component

const api = apiQuery('/users')

// pass error into your bespoke component
if (api.error) return <Error error={error}/>
msmoore
  • 396
  • 2
  • 12
  • Thanks for your answer but I am using axios interceptor therefore above solution won't work as you have written a code for sample axios. I am trying to create a generic error handler wrapper through axios interceptor – Gurpinder Sep 01 '22 at 16:05
  • That's not going to work unless you create global state to store the error on any response and then pull from that state within a react component. But that's going to create a global error on all API requests BEFORE the error is resolved. There is no need for an interceptor here as you don't want the request to continue in the event of X type of error. Here is a good explanation of what interceptors do https://stackoverflow.com/questions/52737078/how-can-you-use-axios-interceptors – msmoore Sep 01 '22 at 16:11
  • I am able to call react-toastify inside interceptors and its working. However, I want to call my custom component on error – Gurpinder Sep 01 '22 at 16:46