I am retrieving data from a booking api where the availability of rooms changes every time. What I am doing is retrieving the data every 1 second using setInterval.
const interval = setInterval(getData, 1000);
which works fine, but I thought it would be better if there was a way to only retrieve if there was an update or change to the data api I was retrieving. I've looked everywhere but I can't find anything about this .
For the server side, say I fetch data from https://api.publicapis.org/entries
using Express and make some changes to the data and now my data is available from https://localhost:3001/api/entries
and I consume it and display what I want using React.
Let's say that https://api.publicapis.org/entries
changes its data every time, how can I recover when only the data changes, so that in https://localhost:3001/api/entries
the data changes accordingly.
CodePudding user response:
I recommend you to use QueryCache
mechanism from React Query
(https://react-query.tanstack.com/reference/QueryCache#_top), it's very powerful feature because by default every query result is cached for five minutes and relies on that cache for subsequent requests.
React query knows that the server data might have updated and the cache might not contain the latest data so a background refetch is triggered for the same query and if the fetch is successful the new data is updated in the UI. Since our data is the same as the cached data we don't see any change in the UI...
YouTube video tutorial as a reference
CodePudding user response:
I think you can do something from both server-side and client-side, fro client-side, use setTimeout instead of setInterval, that can let you send next request only if get the last response, for example:
let timeout
function getData() {
// await request here..
timeout = setTimeout(getData, 1000)
}
and then, query new data with the last update data to the server, so that the server-side could know if there any update data need to send to you. If you want the server notices you when should you get the update, I think you must use sockets.