I am retrieving data from a booking API where room availability changes frequently. Right now, I am fetching the data every 1 second using setInterval, like this:
const interval = setInterval(getData, 1000);
This works fine, but I want to optimize the process by only fetching the data when there’s an actual change in the API response.
I fetch data from https://api.publicapis.org/entries using Express. I process the data and expose it via my own API: https://localhost:3001/api/entries. My React frontend consumes this data and displays it.
Since the source API (https://api.publicapis.org/entries) updates at random intervals, I want to detect when it changes and update my API (https://localhost:3001/api/entries) accordingly—without fetching every second
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...