简体   繁体   中英

Fetch data from external Api with reactjs hooks in every 10 seconds

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])

You can use a useRef hook 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM