PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, October 13, 2022

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

 October 13, 2022     axios, interceptor, reactjs     No comments   

Issue

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.



Answered By - Gabriele Petrioli
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing