我在使用RTK查询时遇到了另一个问题。我们最初使用get请求获取数据。一旦结果添加该高速缓存中,我们希望添加WebSocket连接并侦听任何更改。但我在文档中唯一能找到的是,只是通过.push
添加更多条目。
但我们必须更新已经存在的数据。
数据的结构为:
[
{
resources: event.resources, // Array
events: event.events, // Array
resourceTimeRanges: event.resourceTimeRanges, // Array
calendars: event.calendars, // Array
project: event.project, // Array
},
];
通过WebSocket我们只得到对象的事件属性的改变。所以我们必须更新事件数组中的一个条目。它看起来会是什么样子?
我方代码:
async onCacheEntryAdded(arg, { updateCachedData, cacheDataLoaded, cacheEntryRemoved }) {
const state = store.getState();
const currentUser = state.user.uuid;
console.log(currentUser);
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) => {
schedulerData.util.updateData('getSchedulerEvents', undefined, (draft) => {
// Test data
const newEvent = { id: 2, name: 'newName' };
// How do i update data here???
});
updateCachedData((draft) => {
console.log(draft);
});
};
// client-side
socketClient.emit('schedulerRoom', 'join');
socketClient.on('scheduler', (payload) => {
console.log('Joined room!');
console.log(payload);
listener(payload);
});
} catch (e) {
console.log(e);
// 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
},
非常感谢您的建议。
1条答案
按热度按时间x6h2sr281#
他们的documentation中有一个WebSocket示例