2021年4月11日星期日

How to detect server data changes without refreshing browser or using useEffect in React?

In a React project, I'am fetching data from particular api consider some 'https://www.api-example.com' (just an example, not real url), with method:get, apiKey, authorization and all those things. Now to be more specific, the json data from the server is displayed to front side in React code, but, how to detect changes when json data changes after every minute or seconds or after hour or no changes.

Consider simple example, I am requesting for some Vide Call(VC) request to some person, and the data I receive from that person is in JSON format and has values such as "vc_status":"accepted" or "vc_status":"rejected" or "vc_status":"reshedule", whatever it maybe. Its based on the person choice, to select the desired data. Maybe he accepts request after 1 minute or 30 minutes or rejects or reshedules. My duty is to fetch that data and accordingly reflect to UI.

Now to get data from that person, following are the methods I used: Method 1: useEffect()

const [newRequest, setNewRequest] = useState("")    const newData = () => {  try {  fetch(`https://www.api-example.com/video/requests`,{  method: get,  headers: {     ApiKey:'hbhasdgasAsas',     Authorization: '......'  }  }).then((data) => data.json()).then((data) => setNewRequest(data.vc_request))  }  }    useEffect(() => {  newData()  })  

Then use newRequest data later in the code

Not feasible: useEffect is quite resource intensive and freezes the server at some particular time

Method 2: setInterval()

/* Same code as above, only few changes */

useEffect(() => {  setInterval(() =>{   newData()  }, 10000)  }, [])  

Not feasible: Here the server utilization is intensive although after 10 seconds but, still it freezes server

Ultimately My intention is to get VC status and accordingly reflect on the front-side without using useEffect or setInterval, even though its used but, should not be resource intensive. My duty is to manage only Front-side and fetch data from Server and reflect to UI

So what is the best optimal solution to get 'changed json data' from server and display to the front. Any solution highly appreciated

https://stackoverflow.com/questions/67052159/how-to-detect-server-data-changes-without-refreshing-browser-or-using-useeffect April 12, 2021 at 11:04AM

没有评论:

发表评论