2

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?

1

1 Answer 1

2

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.

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

4 Comments

Why do you mix async/await and use of .then at the same time? Whenever you put await keyword before function, the other line will wait until execution is completed. Async/await was introduced to get rid of .then() pattern.
You can simply use const res = await fetch('https...') and simply do anything with that res on the next line, which will await fetch execution.
this fetches the data on load, but i don't see how it continually polls for updated data as was requested in the question (he is running axios every x seconds to pull new data)
For realtime updates websocket could be used, but the question is poorly formulated and it is not clear it's indeed what needs to be done. Backend is briefly mentioned, but what kind of backend? Is it even nodejs? Is it firebase, something else? Can he make changes to the backend? Here is an article covering it in detail for nodejs and react: blog.logrocket.com/websocket-tutorial-real-time-node-react

Your Answer

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