Home > Enterprise >  Best way to run a function every 60 seconds?
Best way to run a function every 60 seconds?

Time:08-27

I took a basic react class and looking to make some adjustments to it. Currently, the function is run when clicking my button. I'd rather it run automatically every 60 seconds. I've read about the setInterval() function but I'm unsure exactly where it needs to be run.

Do I just use setInterval() within my render() to run myfunction() every 60s? ie, something like:

    render(){
     return(
       setInterval(function(){
             myFunction();
       }, 60000);
       //Show updated this.state.price here
     );
    }

Or should I be approaching this differently? Can't get it to work, either way. Here is the majority of my code:

  componentDidMount() {
    this.getPrice();
  }

  getPrice() {
    this.setState({ isGettingPrice: true });
    fetch("https://api.coindesk.com/v1/bpi/currentprice.json", {
      method: "GET",
      headers: {
        Accept: "application/json"
      }
    })
      .then((response) => response.json())
      .then((json) => {
        this.setState({
          price: json.bpi.USD.rate,
          time: json.time.updated,
          isGettingPrice: false
        });
      });
  }

  onGetPrice() {
    this.getPrice();
  }

  render() {
    console.log("----- RENDER ------");

    return (
      <div>
        <button onClick={this.onGetPrice} disabled={this.state.isGettingPrice}>
          Get price
        </button>

        <p>
          {this.state.isGettingPrice
            ? "Loading price..."
            : "$"   this.state.price}
        </p>
        <p>{"Updated "   this.state.time}</p>
      </div>
    );
  }

CodePudding user response:

Try and add your setInterval function to your componentDidMount function. Returning the setInterval function in your render doesn't work because it is expecting JSX.

CodePudding user response:

You don't put it in render method, follow the example and see if you have other questions. This is a link to code pen with answers to update every 1000 second. https://codepen.io/landingheart-the-animator/pen/QWmReJm

import React, { useRef, useEffect, useState } from "https://cdn.skypack.dev/[email protected]";
import ReactDOM from "https://cdn.skypack.dev/[email protected]";

const App = () => {
  const [counter, setCounter] = useState(0)
  useEffect(() => {
  const interval = setInterval(() => {
    setCounter(counter   1)
  }, 1000);
  return () => clearInterval(interval);
}, [counter]);
  return(
    <div className="box">
      <h1>The Button has a ref</h1>  
      <p>counter {counter}</p>
    </div>
  );
}

  • Related