Updating a cache entry without knowing the original params that generated it #4837
-
I have a situation where I want a mutation to optimistically update all entries in the query cache that contain an object matching the ID, but I don't want to have to pass the original query arguments that fetched in the first place, for a variety of reasons. I came up with the following as a quick proof of concept but it feels really gross. async onQueryStarted(id, api) {
const state = api.getState();
const patchResults: { undo: () => void }[] = [];
Object.entries(state.api.queries)
.forEach(([k, v]) => {
const [_, s] = /^models\((.*)\)$/.exec(k) || [];
if (s != null && (v?.data as Model[]).find(b => b.id === id)) {
patchResults.push(
api.dispatch(
// this also complains about the result of JSON.parse not matching the type of the queryArgs, even though it ultimately works since it results in the same key
apiSlice.util.updateQueryData('models', JSON.parse(s), draft => {
const d = draft.find(m => m.id === id);
if (d) {
// modify state here
}
}),
),
);
}
});
try {
await api.queryFulfilled;
} catch {
patchResults.forEach(p => p.undo());
}
}, I thought maybe adding a hook in async onCacheEntryAdded(args, api) {
await api.cacheDataLoaded;
const key = defaultSerializeQueryArgs({
queryArgs: args,
endpointDefinition: {
queryFn: emptyRequest,
type: DefinitionType.mutation,
},
endpointName: 'models',
});
// theoretical
api.dispatch(cacheKeys.actions.addCacheKey(key));
await api.cacheEntryRemoved;
// also theoretical
api.dispatch(cacheKeys.actions.removeCacheKey(key));
}, This really feels like an abuse of the query cache system on a lot of levels but I:
What other options might I have here? It really feels like the "optimistic update" system suggested in the docs very quickly runs afoul of anything but the simplest, known-ahead-of-time queries. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
You've seen selectInvalidatedBy? https://redux-toolkit.js.org/rtk-query/api/created-api/api-slice-utils#selectinvalidatedby |
Beta Was this translation helpful? Give feedback.
-
Yes, I'm not using tags, so that doesn't address my issue. I don't want it to refetch anything. I should have clarified that in my initial post. Edit: Though right next to it is |
Beta Was this translation helpful? Give feedback.
Here's a simplified version of the function I'm using to update the cache, since the precise mutation will depend on which model I'm dealing with and the operation in question: