- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
有人可以解释一下如何将 websocket 消息中的数据接收连接到来自 RTK 查询 api 端点的钩子(Hook)的数据对象吗?
我们不需要存储收到的消息,我们只想将其传递到 useGetWebsocketResponseQuery Hook 的数据参数中,以便我们可以在 UI 中触发通知。
reducerPath: 'someApi',
baseQuery: baseQueryWithReauth,
endpoints: (builder) => ({
getWebsocketResponse: builder.query<WebsocketResult, void>({
queryFn: () => ({data: {}),
async onCacheEntryAdded(arg, { updateCachedData, cacheDataLoaded, cacheEntryRemoved }) {
try {
// wait for the initial query to resolve before proceeding
await cacheDataLoaded;
const socket = io('http://url', {});
socket.on('connect', () => {
console.log('socket connected on rtk query');
});
socket.on('message', (message) => {
console.log(`received message: ${message}`);
// THIS IS WHERE THE DATA NEEDS TO BE WIRED UP TO THE HOOK BUT HOW?
});
await cacheEntryRemoved;
} catch {
// no-op in case `cacheEntryRemoved` resolves before `cacheDataLoaded`,
// in which case `cacheDataLoaded` will throw
}
}
}),
// Export hooks for usage in functional components, which are
// auto-generated based on the defined endpoints
export const {
useGetWebsocketResponseQuery
} = someApi;
感觉这在 socket.on('message', {}) 处理程序中应该是可能的,但是怎么做呢? updateCachedData 方法似乎应该是可行的方法,但我不确定如何实现它。
感谢所有帮助:-)
非常感谢,
山姆
更新来自@phry 的解决方案
问题是 queryFn 中定义的数据需要匹配从 cacheDataLoaded 附加的数据的形状,即它应该是这样的:-
queryFn: () => ({data: { messages: [] }),
和
socket.on('connect', () => {
updateCachedData((currentCacheData) => {
currentCacheData.messages.push(message);
});
});
最佳答案
在阅读 redux 工具包文档后,我发现到目前为止你应该使用 createEntityAdapter为缓存数据创建数据库架构,并在从套接字收到消息后使用 CRUD 更新该数据库(缓存)函数,例如,首先触发 API 查询并获取数据,您可以使用 createEntityAdapter
的 addOne
或 addMany
,然后当从套接字接收到数据时您可以使用 setOne
来为 setMany
更新 updateCachedData
中的缓存数据。通过这样做,use[yourWhatEver]Query
中的实际数据首先在查询获取 API 时更新,然后每次从套接字接收数据时更新。
import { createApi } from '@reduxjs/toolkit/query/react';
import axiosBaseQuery from 'api/axiosBaseQuery';
import { createEntityAdapter } from '@reduxjs/toolkit';
const instrumentsAdapter = createEntityAdapter({
selectId: (item) => item?.state?.symbol
});
export const marketApi = createApi({
reducerPath: 'api/market',
baseQuery: axiosBaseQuery(),
endpoints: (builder) => ({
getInstrumentByRefId: builder.query({
query: (refId) => ({
url: `/market/instruments/${refId}/summary`,
method: 'get'
}),
transformResponse: (res) => {
return instrumentsAdapter.addMany(instrumentsAdapter.getInitialState(), [res]);
},
async onCacheEntryAdded(arg, { updateCachedData, cacheDataLoaded, cacheEntryRemoved }) {
// arg === refId
const payload = `instruments.${arg}.summary`;
// create a websocket connection when the cache subscription starts
const ws = new WebSocket('wss://[domain.com]/api/notification/ws');
let waitTimer = null;
const waitForConnection = (callback, interval) => {
clearTimeout(waitTimer);
if (ws && ws.readyState === 1) {
callback();
return;
}
// optional: implement backoff for interval here
waitTimer = setTimeout(() => {
waitForConnection(callback, interval);
}, interval);
};
try {
// wait for the initial query to resolve before proceeding
await cacheDataLoaded;
// when data is received from the socket connection to the server,
// if it is a message and for the appropriate channel,
// update our query result with the received message
const listener = (event) => {
const data = JSON.parse(event.data);
// eslint-disable-next-line no-console
// console.log('data', data);
// if (!isMessage(data) || data.channel !== arg) return;
updateCachedData((draft) => {
// eslint-disable-next-line no-unused-vars, no-param-reassign
if (data.value) {
instrumentsAdapter.setMany(draft, [data.value]);
}
});
};
waitForConnection(() => {
ws.send(
JSON.stringify({
id: '1',
type: 'SUBSCRIBE',
path: payload
})
);
}, 100);
ws.onmessage = listener;
// ws.addEventListener('message', listener);
} catch (err) {
console.log('err', err);
// no-op in case `cacheEntryRemoved` resolves before `cacheDataLoaded`,
// in which case `cacheDataLoaded` will throw
}
// cacheEntryRemoved will resolve when the cache subscription is no longer active
await cacheEntryRemoved;
// perform cleanup steps once the `cacheEntryRemoved` promise resolves
ws.close();
}
}),
getCandles: builder.query({
query: ({ refId, bucket, end, limit = 1 }) => ({
url: `/market/instruments/${refId}/candles?bucket=${bucket}&end=${end}&limit=${limit}`,
method: 'get'
})
})
})
});
export const {
useGetMarketMapQuery,
useGetInstrumentByRefIdQuery,
useGetInstrumentsQuery,
useGetCandlesQuery
} = marketApi;
在 React 组件中你可以更新值
function MyReactComponent() {
// data will gets updated every time socket data received.
const { data } = useGetInstrumentByRefIdQuery('IRO1SIPA0001');
return JSON.stringify(data);
}
希望对您有所帮助。
关于javascript - 如何在收到 websocket 消息时更新从 RTK 查询返回的 Hook 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72292848/
假设浏览器被强制终止,并且没有关闭消息发送到 Tornado 服务器。 Tornado 怎么知道(或者它甚至知道?)这个连接已经在客户端终止了?翻看Tornado websocket code这对我来
我目前正在开发一款使用 WebSockets 的基于浏览器的多人游戏。我的首要任务是低延迟以及与各种平台和网络设置的兼容性。 但是我正在做密码验证。我还有聊天功能,我认为玩家的隐私很重要。因此,我认为
我必须设计一个解决方案,允许通过远程托管的网络应用程序读取本地传感器生成的实时数据。 设计仍在进行中:传感器的数据可以由安装在客户端计算机上的 Windows 应用程序/服务处理,或者由位于客户端计算
WebSocket的端口是什么? WebSocket 使用什么协议(protocol)? 当防火墙阻止除 80 和 443 端口之外的所有端口时,WebSocket 是否工作? 最佳答案 What i
有一个 fantastic answer其中详细介绍了 REST apis 的工作原理。 websockets 如何以类似的细节工作? 最佳答案 Websocket 创建并代表了服务器和客户端之间双向
请原谅我的无知,因为我在负载均衡器和 websockets 方面的经验有限。我试图了解客户端如何通过 websockets 连接到位于负载均衡器后面的服务器集群。 我对负载均衡器的理解是它们就像反向代
我正在尝试使用 websocket 发送音频消息,我应该将音频流更改为什么类型的消息,以便我可以使用套接字发送? 如果我直接使用 websocket.send(audio),我会得到一个错误“DOME
我对 WebSockets 的前景感到非常兴奋。由于我在过去构建了一些基于桌面套接字的游戏和 Web 游戏,因此我热衷于将这两种方法结合起来构建基于 Web 的多人游戏,而无需长时间轮询。 自从 Fi
我读过很多关于实时推送通知的文章。并且简历是 websocket 通常是首选技术,只要您不关心 100% 的浏览器兼容性。然而,one article指出 Long polling - potenti
我很难找到文档或教程,以便通过网络套接字发送文件。 这是我的JS: ['dragleave', 'drop'].forEach(event_name => document.addEventListe
我正在使用 Dart 的 WebSocket 类(dart:io 和 dart:html 版本)连接到 Dart WebSocket 服务器。当我让客户端使用自定义关闭代码和原因关闭 Web 套接字连
谷歌浏览器框架是否支持 websocket? 最佳答案 答案是肯定的,Chrome Frame supports websockets .我不确定,但这也可能取决于您安装的 Chrome 版本。我有
是否可以在同一应用程序(同一端口)中托管一个普通 Bottle 应用程序和一个 WebSocket 应用程序(例如: https://github.com/defnull/bottle/blob/ma
我有一个支持网络套接字的服务器。浏览器连接到我的网站,每个浏览器都会打开一个到 www.mydomain.example 的 Web 套接字。这样,我的社交网络应用程序就可以向客户端推送消息。 传统上
我是 Websockets 新手。在阅读有关 websockets 的内容时,我无法找到一些疑问的答案。我希望有人能澄清一下。 websocket 是否仅将数据广播到所有连接的客户端而不是发送到特定客
客户端可以通过 websockets 连接到服务器多长时间?是否有时间限制,它们是否有可能连在一起多年? 最佳答案 理论上,WebSocket 连接可以永远持续下去。假设端点保持正常运行,长期存在的
我正在尝试使用 websockets 制作自己的聊天客户端,并认为我会从 Tomcat 7 websocket chat example code. 开始。 .我已经成功编译并部署了ChatAnnot
我有一个使用 AdSense 的应用程序,据我所知,由于 AdSense 政策,不允许进行轮询。我想知道如果我使用 WebSockets 并且服务器在创建新数据时向客户端发送新数据并且在客户端上显示新
在 servlet 世界中,我会使用 cookie 和 HttpSession 之类的东西来识别谁在访问我的 Restful 服务以将请求路由到正确的数据。将 Sec-WebSocket-Key 用作
我必须使用 websocket 实现一个聊天应用程序,用户将通过群组聊天,可以有数千个群组,并且一个用户可以在多个群组中。我正在考虑两种解决方案: [1] 对于每个群聊,我创建一个 websocket
我是一名优秀的程序员,十分优秀!