-
Here's my use case: I have a list endpoint with pagination. It is called with parameters like {
limit: 10,
offset: 0,
orderBy: 'title',
orderDirection: 'asc'
} and these values are only stored in a component's state. The result looks something like this: {
totalRecords: 123,
records: [{ id: '12345', ... }]
} There is also a mutation for changing a specific entry by id. But the problem is, I don't have the arguments I called the query with when I call Ideally I'd want to have an array of all cache entries for the list endpoint, so that I could find and replace all of them that have the element with id I changed. Is there's a way to do that or add optimistic update in any other way? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
You could just extract them from the Redux store slice, like doing normal Redux. |
Beta Was this translation helpful? Give feedback.
-
Created a helper function to get them. Typescript isn't my forte so it's not the most clean or user-friendly way to do it but hey it works. Here's the function in case someone needs it: import { Api } from '@reduxjs/toolkit/dist/query';
import api from 'service/api/api';
import store from 'service/store';
function getQueryCacheEntries<
Endpoints extends keyof Api<any, any, any, any>['endpoints'] = string
>(query?: Endpoints) {
const { queries } = store.getState()[api.reducerPath];
let allQueries = [];
for (let queryCache of Object.values(queries)) {
if (!query || queryCache?.endpointName === query) {
allQueries.push(queryCache);
}
}
return allQueries;
}
export default getQueryCacheEntries; The Here's how I use it: onQueryStarted: (
{ id, ...patch }: UpdateUserRequest,
{ dispatch, queryFulfilled }
) => {
const queries =
getQueryCacheEntries<keyof typeof userApi.endpoints>('users');
for (let query of queries) {
const data = query?.data as PaginatedData<UserResponse>;
if (!query?.data || !find(data.records, { id })) return;
const patchResult = dispatch(
userApi.util.updateQueryData(
'users',
query.originalArgs as PaginatedRequest,
(draft) => {
const index = findIndex(draft.records, { id });
draft.records[index] = {
...draft.records[index],
...patch,
};
}
)
);
queryFulfilled.catch(patchResult.undo);
}
}, Everything that starts with a capital here is a type, I could make a more specific version for updating data with pagination, but I think it makes sense to have a function like this too |
Beta Was this translation helpful? Give feedback.
Created a helper function to get them. Typescript isn't my forte so it's not the most clean or user-friendly way to do it but hey it works. Here's the function in case someone needs it: