1

I use React js hooks to fetch data from api every 10 seconds in UseEffect. The problem is that it takes 10 seconds to do the state update first. So before the setInterval function, I need to fetch the data once the component is not rendered.

Code part is here:

function getList() {
  return axios.post('http://localhost:5000/getParameters', { no: no, name: name })
  .then(data => data.data)
}
function getParams() {
  return axios.post('http://localhost:5000/getParametersSite', { no: no, name: name })
  .then(data => data.data)
}



useEffect(() => {
  let mounted = true;
  let isMounted = true
  const intervalId = setInterval(() => {
  getParams()
  .then(itemsa => {
    if(mounted) {
      setParams(itemsa)
    }
  })

  getList()
    .then(items => {
      if(mounted) {
        setMenuData(items)
      }
    })

}, 10000)
return () => {
  clearInterval(intervalId);
  isMounted = false 
  mounted = false;
}

}, [menuData,params])

1 Answer 1

1

You can use a useRefhook to know if it is the first render. like this:

 const firstUpdate = useRef(true);
  
  useEffect(() => {
  let mounted = true;
  let isMounted = true
    if (firstUpdate.current) {
      firstUpdate.current = false;
      getParams()
      .then(itemsa => {
        if(mounted) {
          
          setParams(itemsa)
        }
      })
    
      getList()
        .then(items => {
          if(mounted) {
           
            setMenuData(items)
          }
        })
     
    }
   
    
    const intervalId = setInterval(() => {
    getParams()
    .then(itemsa => {
      if(mounted) {
        console.log("getParams",itemsa);
        
        setParams(itemsa)
      }
    })
  
    getList()
      .then(items => {
        if(mounted) {
          console.log("setParams",items);
          setMenuData(items)
        }
      })
  
  }, 10000)
  return () => {
    clearInterval(intervalId);
    
    mounted = false;
  }
  
  }, [menuData,params])

like explain in react doc :

useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.

So no matter if your component render again.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.