How to call an API every minute for a Dashboard in REACT

For those looking for functional components. You can update the state every n time by creating a setInterval and calling this in the useEffect hook. Finally call the clearInterval method in the clean up function

import React, { useEffect, useState } from "react";

import Panelone from "./Components/Panelone";
import Paneltwo from "./Components/Paneltwo";

function App() {
  const [state, setState] = useState({
    panelone: [],
    paneltwo: [],
  });

  const getData = async () => {
    try {
      const res = await fetch("https://api.apijson.com/...");
      const blocks = await res.json();
      const dataPanelone = blocks.panelone;
      const dataPaneltwo = blocks.paneltwo;

      setState({
        panelone: dataPanelone,
        paneltwo: dataPaneltwo,
      });
    } catch (e) {
      console.log(e);
    }
  };

  useEffect(() => {
    const intervalCall = setInterval(() => {
      getData();
    }, 30000);
    return () => {
      // clean up
      clearInterval(intervalCall);
    };
  }, []);
  return (
    <div className="App">
      <div className="wrapper">
        <Panelone panelone={state} />
        <Paneltwo paneltwo={state} />
      </div>
    </div>
  );
}

export default App;

Move the data fetch logic into a seperate function and invoke that function using setInterval in componentDidMount method as shown below.

  componentDidMount() {
    this.loadData()
    setInterval(this.loadData, 30000);
  }

  async loadData() {
     try {
        const res = await fetch('https://api.apijson.com/...');
        const blocks = await res.json();
        const dataPanelone = blocks.panelone;
        const dataPaneltwo = blocks.paneltwo;

        this.setState({
           panelone: dataPanelone,
           paneltwo: dataPaneltwo,
        })
    } catch (e) {
        console.log(e);
    }
  }

Below is a working example

https://codesandbox.io/s/qvzj6005w


In order to use await, the function directly enclosing it needs to be async. According to you if you want to use setInterval inside componentDidMount, adding async to the inner function will solve the issue. Here is the code,

 async componentDidMount() {
          try {
            setInterval(async () => {
              const res = await fetch('https://api.apijson.com/...');
              const blocks = await res.json();
              const dataPanelone = blocks.panelone;
              const dataPaneltwo = blocks.paneltwo;

              this.setState({
                panelone: dataPanelone,
                paneltwo: dataPaneltwo,
              })
            }, 30000);
          } catch(e) {
            console.log(e);
          }
    }

Also instead of using setInterval globally, you should consider using react-timer-mixin. https://facebook.github.io/react-native/docs/timers.html#timermixin


I figured I'd chime in with a slightly revised approach that uses recursion via a setTimeout call within the function block. Works the same...maybe slightly cleaner to have the function call itself from within, instead of doing this elsewhere in your code?

This article explains the reasoning in a bit more depth...but I've been using this approach for several dashboards at work - does the job!

Would look something like this:

class MyComponent extends React.Component
//create the instance for your interval
intervalID;
constructor(props) {
    super(props);
    this.state = {
        data: [],
        loading: false,
        loadingMap: false,

        //call in didMount...
        componentDidMount() {
          this.getTheData()
        }

 getTheData() {
 //set a loading state - good practice so you add a loading spinner or something
   this.setState({loading: true}), () => {
 //call an anonymous function and do your data fetching, then your setState for the data, and set loading back to false
   this.setState({
       data: fetchedData,
       loading: false
       )}     }
 //Then call the function again with setTimeout, it will keep running at the specified //interval...5 minutes in this case
            this.intervalID = setTimeout(
              this.getTheData.bind(this),
              300000
            );

          }
        }
        //Important! Be sure to clear the interval when the component unmounts! Your app might crash without this, or create memory leaks!
        componentWillUnmount() {
          clearTimeout(this.intervalID);
        }

Sorry if the formatting got a little off. Haven't tried this with Hooks yet but I think you'd have a similar implementation in a useEffect call? Has anyone done that yet?