Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

axios react get real-time data display

I made an Axios get request to get data to display it with react

export function Wareh() {
  const [wareh, setWareh] = useState([{}]);

  useEffect(() => {
    axios.get("http://localhost:1515/wareh").then((response) => {
      setWareh((existingData) => {
        return response.data;
      });
    });
  }, []);
  return wareh;
}

the problem here if i update my data i have to refresh the page to see the udpate Here is my question :

how to make itto be like r like if any changes happens in the database it reflects the get request.

like image 542
Red bad coder Avatar asked Aug 23 '26 06:08

Red bad coder


1 Answers

There are 3 ways to achieve this. Either you can do it using

  1. Long pooling

In this technique, you can set Interval and call the same endpoint to refresh the data with the passage of time.

setInterval(() => fetchWareh(), 5000)

Let's assume you can shift your Axios call to a function named: fetchWareh and call the same function after every 5 seconds

  1. Server Sent Event This is approach is quite similar to the first approach. You read more about from here:

https://www.w3schools.com/html/html5_serversentevents.asp

  1. Implement socket on server & client

A most recommended to do it through socket.io to fetch real-time data.

Socket Documentation Here

like image 68
ferozpuri Avatar answered Aug 25 '26 20:08

ferozpuri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!