Home > Back-end >  Correct way to clear interval in component did mount in React
Correct way to clear interval in component did mount in React

Time:09-21

Im trying to clear an interval when the component is unmounted in a class based component in react. I have done some research on this and saw that in the componentWillUnmount lifecycle function, people are storing the actual function in a variable instead of just straight away clearing the interval. For example:

      componentDidMount() {
        const { stock } = this.props;
// Fetch data once user lands on page
        this.fetchData(stock);
// Fetch data every hour
        setInterval(() => {
          this.fetchData(stock);
          console.log('setInterval ran');
        }, 3600000);
      }
   
    
      componentWillUnmount() {
        const { stock } = this.props;
// Remove interval
        const refreshFetch = clearInterval(this.fetchData(stock));
        console.log('setInterval cleared');
      }
    
      async fetchData(stock) {
        const data = await getAvgPriceHistory(stock);
        if (data && data[stock].length) {
          const dataArray = data[stock].map((arr) => {
            return arr[1];
          }).reverse();
          this.setState({
            data: dataArray,
            isLoaded: true
          });
        } else {
          // straight line if not found.
          this.setState({
            data: [1, 1],
            isLoaded: true
          });
        }
        console.log('Data fetched!');
      }

Meanwhile, the way I am used to doing this in the componentWillUnmount function without defining a variable like so:

      componentWillUnmount() {
        const { stock } = this.props;
// Remove interval
       clearInterval(this.fetchData(stock));
        console.log('setInterval cleared');
      }

Is there any benefits to doing one or the other?

CodePudding user response:

setInterval return an id. You can use it with clearInterval to destroy it.

https://developer.mozilla.org/en-US/docs/Web/API/setInterval

let intervalId;

...

intervalId = setInterval(fn, time);

...

clearInterval(intervalId);
  • Related