user18036812
user18036812

Reputation:

How can I refresh the data(API) in react js?

Right now I am calling the data from the backend but when the backend updates any value its also not refect in the UI

Later on, In useEffect, I am calling Axios with set interval but it continuously runs in the networks tab so I want when the server updates anything it updates without using set interval. How can I update the table component?

Upvotes: 2

Views: 5489

Answers (1)

Max Larionov
Max Larionov

Reputation: 474

What you are looking for is something like this:

const [populationData, setPopulationData] = useState([]);
async function fetchData() {
    fetch(
      'https://datausa.io/api/data?drilldowns=Nation&measures=Population'
    )
      .then((res) => res.json())
      .then((res) =>
        setPopulationData(res.data)
      );
  }
  useEffect(() => {
    fetchData();
  }, []);

When you will set populationData with setPopulationData it will trigger a re-render and you should be able to display your props in UI.

If I understood it correctly you are running into an infinite loop of axios requests? Notice the [] as a second argument of useEffect? This is going to solve the infinite loop problem for you.

You can read about dependencies and the empty array part here in the doc: https://reactjs.org/docs/hooks-effect.html

PS: you can also use async/await to handle the request. Whichever is better is just an opinion. It's up to you to decide.

Upvotes: 2

Related Questions