仅在 NodeJS 更新时从 API 获取数据
我正在从预订 api 检索数据,其中房间的可用性每次都会发生变化。我正在做的是使用 setInterval 每 1 秒检索一次数据。
const interval = setInterval(getData, 1000);
效果很好,但我认为如果有一种方法可以仅在我检索的数据 api 有更新或更改时进行检索,那就更好了。我到处都找过了,但找不到任何与此有关的信息。
对于服务器端,假设我使用 Express 从 https://api.publicapis.org/entries
获取数据并对数据进行一些更改,现在我的数据可从 https:/ /localhost:3001/api/entries
我使用它并使用 React 显示我想要的内容。
假设 https://api.publicapis.org/entries
每次都会更改其数据,当只有数据更改时我如何恢复,以便在 https://localhost:3001 /api/entries
数据会相应更改。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我建议您使用
querycache
来自React Query
的机制“ nofollow noreferrer”> https://reaeact-query.tanstack.com/reference/querycache#_top ),因为默认情况下,每个查询结果都被缓存了五分钟,并且依赖于该缓存的每个查询结果请求。React查询知道服务器数据可能已经更新,并且缓存可能不包含最新数据,因此触发了背景refetch
相同的查询,如果获取成功,则在UI中更新了新数据。由于我们的数据与缓存数据相同,因此我们在UI中看不到任何变化...
youtube视频教程作为参考
I recommend you to use
QueryCache
mechanism fromReact 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
我认为你可以从服务器端和客户端做一些事情,从客户端,使用 setTimeout 而不是 setInterval,这样可以让你仅在获得最后一个响应时发送下一个请求,例如:
然后查询新数据将最后的更新数据发送到服务器,以便服务器端知道是否有更新数据需要发送给您。如果您希望服务器通知您何时应该获得更新,我认为您必须使用套接字。
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:
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.