3

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 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I;m using class component can i use it inside componentdidmount instead of useeffect?
Sure you can, useEffect is only a hook, I invite you to check the reactjs website to understand it: reactjs.org/docs/hooks-effect.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.