Display data without refreshing page in React

38 Views Asked by At

I have data tables that are updated every few seconds in my db. I want to display them in react in real time - when there is an update in the db, the information displayed in react will be updated automatically without refreshing the page. for example-

 useEffect(() => {
         const apiUrl = 'http://localhost:3001/main-table/receptionQueue';
         axios.get(apiUrl)
             .then(response => {
                 setQueue(response.data);
             })
             .catch(error => {
                 console.error('Error fetching reception queue data:', error);
             });
      }, []);

When I run the above code - it's one get request. And when I remove the square brackets it's a lot of get requests without a break- Which causes slowness and high resource consumption. Does anyone know how to write it in such a way that only when there is an update in the database, a get request will be performed on the client side?

I use: database - MongoDb , backend - Node.js , frontend - React

Any solution would really help me! Thank you:)

I tried to make a webSocket but it got a bit complicated....

1

There are 1 best solutions below

2
Talya Sterman On

1.Use useState()

  1. When do you want to get new data? every few seconds? if so, put it all in a timer

Here is an example:

  const [data, setData] = useState();
  useEffect(() => {
    const apiUrl = "http://localhost:3001/main-table/receptionQueue";
    const interval = setInterval(function () {
      axios
        .get(apiUrl)
        .then((response) => {
          setData(response.data);
        })
        .catch((error) => {
          console.error("Error fetching reception queue data:", error);
        });
    }, 5000);
    return () => {
      clearInterval(interval);
    };
  }, []);