Skip to content

Commit

Permalink
Merge pull request #25 from lifeomic/paginated-cache
Browse files Browse the repository at this point in the history
feat: support updating cache of a infinite query entry
  • Loading branch information
jkdowdle authored Jun 12, 2023
2 parents cd61181 + 8488968 commit d5bf22c
Show file tree
Hide file tree
Showing 5 changed files with 300 additions and 132 deletions.
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -455,6 +455,18 @@ cache.updateCache(
);
```
When dealing with a cache entry that was initiated via `useInfiniteAPIQuery` (paginated) prefer using `updateInfiniteCache` which otherwise behaves the same as `updateCache`
```typescript
const cache = useAPICache();

cache.updateInfiniteCache(
'GET /list',
{ filter: 'some-filter' },
(current) => {...},
);
```
**Note**: if performing a programmatic update, _no update will occur_ if there is not a cached value.
## Test Utility API Reference
Expand Down
27 changes: 18 additions & 9 deletions src/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ const createQueryFilterFromSpec = <Endpoints extends RoughEndpoints>(
}

const payloadsToInvalidate = endpoints[entry.route];

if (!payloadsToInvalidate) {
return false;
}
Expand All @@ -42,23 +43,21 @@ const createQueryFilterFromSpec = <Endpoints extends RoughEndpoints>(
}),
});

export const INFINITE_QUERY_KEY = 'infinite' as const;

export const createCacheUtils = <Endpoints extends RoughEndpoints>(
client: QueryClient,
makeQueryKey: <Route extends keyof Endpoints & string>(
route: Route,
payload: RequestPayloadOf<Endpoints, Route>,
) => InternalQueryKey,
): CacheUtils<Endpoints> => {
return {
invalidateQueries: (spec) => {
void client.invalidateQueries(createQueryFilterFromSpec(spec));
},
resetQueries: (spec) => {
void client.resetQueries(createQueryFilterFromSpec(spec));
},
updateCache: (route, payload, updater) => {
const updateCache: (
keyPrefix?: typeof INFINITE_QUERY_KEY,
) => CacheUtils<Endpoints>['updateCache'] =
(keyPrefix) => (route, payload, updater) => {
client.setQueryData<Endpoints[typeof route]['Response']>(
[makeQueryKey(route, payload)],
[keyPrefix, makeQueryKey(route, payload)].filter(Boolean),
typeof updater !== 'function'
? updater
: (current) => {
Expand All @@ -73,6 +72,16 @@ export const createCacheUtils = <Endpoints extends RoughEndpoints>(
);
},
);
};

return {
invalidateQueries: (spec) => {
void client.invalidateQueries(createQueryFilterFromSpec(spec));
},
resetQueries: (spec) => {
void client.resetQueries(createQueryFilterFromSpec(spec));
},
updateCache: updateCache(),
updateInfiniteCache: updateCache(INFINITE_QUERY_KEY),
};
};
Loading

0 comments on commit d5bf22c

Please sign in to comment.