Continuously Fetch API For new data React Fetch

Viewed 402

I've a dynamic json that changes value continuously. i want to draw chart with that data so i stored the dynamic data to array then draws chart with that array.currently i created serinterval for fetching new data from api.but the problem is it pushes same data again if the new data didn't updated . please guide me how to approach these problem.

React code:

 setInterval(() => {
         fetch('/get.json')
        .then((response) => response.json())
    
        .then(booksList => {
            this.setState({ books: booksList[0].run.data.metrics});
          
            })        
            let floors = [...this.state.dataPoints];
            floors.push({
                y: this.state.books[0].timestamp,
                mAp: this.state.books[0].value
              });
              this.setState({ dataPoints:floors });
      
   },100000);

JSON:

[{
  "run": {
    "info": {},
    "data": {
      "metrics": [
        {
          "key": "mAp",
          "value": 0.005594323437280125,
          "timestamp": "1647000187223",
          "step": "0"
        }
      ],
      "params": [
        {
          "key": "epoch",
          "value": "5"
        }
      ]
      
    }
  }
}
]

The json values are dynamic those values are changing continuosly. please guide me how to solve that.

1 Answers

Try to wrap it inside a useEffect and clear your interval

useEffect(() => {
    const fetchData = async () => {fetch('/get.json')
        .then((response) => response.json())
    
        .then(booksList => {
            this.setState({ books: booksList[0].run.data.metrics});
        };
   const interval =  setInterval(() => {   
          fetchData();
          let floors = [...this.state.dataPoints];
          floors.push({
              y: this.state.books[0].timestamp,
              mAp: this.state.books[0].value
          });
          this.setState({ dataPoints:floors });
   },100000);
    return () => clearInterval(interval);
  });

For the duplicate issue, useEffect will mount and unmount your component to re-render it. You can also set a condition of re-render at the end of the useEffect. Also you should take your fetch function out of your setInterval to avoid conflicts.

Related