Home > other >  react navigate and save history
react navigate and save history

Time:09-27

I am building a React Application with multi-router

Home router call an API in use Effect but when I navigate to another Route and go back to home the request is recall and the component which contain response is reload

is there a way to save history so when I come back the route not calling the API and if it call it, at least not reload the section using response

here my Use-effect

useEffect(() => {

(async () => {

  try{
      const response = await axios.get("user")
        dispatch(setAuth(response.data))
      }
  catch(e){}
  try{
      const response = await axios.get("get_all_posts")
      setpostsInfo(response.data)
  }
  catch(e){}
})()
}, []);

Thanks for help

CodePudding user response:

add this isRun

const [ isRun ,setIsRun ] =useState(true)

useEffect(   () => {
if(isRun){
(async () => {

try{
  const response = await axios.get("user")
    dispatch(setAuth(response.data))
  }
catch(e){}
try{
   const response = await axios.get("get_all_posts")
   setpostsInfo(response.data)
      setIsRun(false)
   }
   catch(e){}
     })()
   }

  }, []);

CodePudding user response:

when you change the route you component unmount so its state is lost. when you go back to the home route the component mount again it's a new instance so you can't hold the information in the component you should hold the information of the number of visiting the page for example or if it's the first time mounting the component in a higher place than the component (the localstorage for example) you can store a key or value to indicate that it's the first time visiting this page and when the compoenent unmount the information stills there. when the component mount again check the existance and validity of the key in the localstorage and you decide whether you send the request or not in the useEffect

  • Related