Unable to clear interval in Expo React native application

So, I am using expo and react-navigation to create an android application. I want to call a function every 1 second but also want to clear the interval according to the response. The code is as follows:

import React,{useEffect,useState} from 'react'; const Home = props => {          const [intervalId,setIntervalId]=useState(null);      useEffect(()=>{         let interval = setInterval(fetchData,1000);         setIntervalId(interval);     },[]);      const fetchData = async () => {         const response = await fetch(''); //fetch data from some URL here         const res = await response.json();                  if(res.someThing) {             clearInterval(intervalId); //clear interval using id stored in state                                        //no errors but does not seem to clear the interval         }     };      return (         //JSX     );  };  

I don’t know why clearInterval is not working here or if I am doing something wrong.

Add Comment
1 Answer(s)

Most likely this is due to res.someThing being "falsey". Without seeing the response it will be hard to debug.

It seems you are trying to achieve a kind of polling. A better way of doing this would be to clear the interval using a clean up function. Example:

function Home() {   const intervalId = useRef(0);   const [value, setValue] = useState(null);    useEffect(() => {     // Clean the interval no matter what     clearInterval(intervalId.current);      // Conditionally set interval     if (value === null) {       intervalId.current = setInterval(fetchData, 1000);     }      // Clean up     return () => clearInterval(intervalId.current);   }, [value]);    async function fetchData() {     const response = await fetch("");     const res = await response.json();     setValue(res.someThing);   }    return null; // Render UI } 

This function does what you want, by clearing the interval when the value from the fetch function is set. It will clear the interval and only set another interval if the value is what you want it to be.

Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.