RTK Query - Delete cached data upon cacheEntryAdded
Answer a question
Currently we have an api endpoint that requests a single 'Group' via ID.
We have a WebSocket subscription set up, and in the onCacheEntryAdded definition, we handle cases where that Group is updated, or deleted.
When we receive an update message from the websocket, we trigger the following;
updateCachedData((draft) => {
draft = response;
}
Which updates the entry, as expected.
However, what is the approach we should use if we want to remove the entry entirely? Upon 'delete' messages from the websocket, I would assume I could simply set draft as undefined, but that doesn't seem to be the case.
Answers
updateCachedData((draft) => {
draft = response;
}
actually does not update anything here in the first place.
updateQueryResults has the same rules as produce from immer or normal createSlice case reducers: you can modify the object in state (or draft in this case), but you cannot reassign the variable itself. If you want to do that, you have to
updateCachedData((draft) => {
return response;
}
instead.
In the same fashion, you can
updateCachedData((draft) => {
return null;
}
too, but that will not remove the full cache entry, it will only set the data to null. (undefined won't work!)
The cache entry will only be removed once there is no more component using it (by not using it with useQuery) - and then it will be removed automatically after 60 seconds.
更多推荐
所有评论(0)