Search code examples
reactjsaxiosinterceptor

How do I give axios interceptors access to my react app's state?


I am using an axios interceptor to handle errors globally, but would like to set the state of my app from the interceptor. Something like:

axios.interceptors.response.use(
   error => {
      AppState.setError(error)
   }
)

function App() {

   [error,setError] = useState()

}

How can I either access the state of App from outside, or alternatively how can I call a function defined within App from the interceptor?

I've tried

axios.interceptors.response.use(
   error => {
      App.setAppErrorState(error)
   }
)

function App() {

   this.setAppErrorState = function(error) {
       // do something with error like set it to state
   }

}

but get the error "TypeError: Cannot set property 'setAppErrorState' of undefined"

I'm not currently using Redux so a solution without using it would be preferable. Any help appreciated!


Solution

  • How about setting the interceptor inside the App component ?

    function App() {
      const [error, setError] = useState();
    
      useMemo(() => {
        axios.interceptors.response.use(
          error => {
            setError(error)
          }
        )
      }, [setError])
    
    
    }
    

    Notice (quote from https://reactjs.org/docs/hooks-reference.html#usememo)

    You may rely on useMemo as a performance optimization, not as a semantic guarantee. In the future, React may choose to “forget” some previously memoized values and recalculate them on next render, e.g. to free memory for offscreen components. Write your code so that it still works without useMemo — and then add it to optimize performance.