Skip to content

Commit

Permalink
Merge pull request #38 from lifeomic/get-cache-data
Browse files Browse the repository at this point in the history
feat: add getCacheData and getInfiniteCacheData cache utils
  • Loading branch information
swain authored Nov 8, 2023
2 parents 0939567 + 9868a99 commit d30ba62
Show file tree
Hide file tree
Showing 4 changed files with 111 additions and 3 deletions.
32 changes: 29 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -472,19 +472,45 @@ cache.updateCache(
);
```
When dealing with a cache entry that was initiated via `useInfiniteAPIQuery` (paginated) prefer using `updateInfiniteCache` which otherwise behaves the same as `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',
'GET /messages',
{ filter: 'some-filter' },
(current) => {...},
);
```
**Note**: if performing a programmatic update, _no update will occur_ if there is not a cached value.
#### `getCacheData`
Get the cached data for a query, if there is any.
```typescript
const cache = useAPICache();

const value = cache.getCacheData(
// Specify the route + payload that you'd like to get the cached value for.
'GET /messages',
{ filter: 'some-filter' },
);

value; // Message[] | undefined
```
When dealing with a cache entry that was initiated via `useInfiniteAPIQuery` (paginated) prefer using `getInfiniteCacheData` which otherwise behaves the same as `getCacheData`.
```typescript
const cache = useAPICache();

const value = cache.getInfiniteCacheData('GET /messages', {
filter: 'some-filter',
});

value; // { pages: Message[]; }
```
## Test Utility API Reference
Expand Down
4 changes: 4 additions & 0 deletions src/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,5 +83,9 @@ export const createCacheUtils = <Endpoints extends RoughEndpoints>(
},
updateCache: updateCache(),
updateInfiniteCache: updateCache(INFINITE_QUERY_KEY),
getCacheData: (route, payload) =>
client.getQueryData([makeQueryKey(route, payload)]),
getInfiniteCacheData: (route, payload) =>
client.getQueryData([INFINITE_QUERY_KEY, makeQueryKey(route, payload)]),
};
};
68 changes: 68 additions & 0 deletions src/hooks.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1123,3 +1123,71 @@ test('passing a function for `client` is supported', async () => {
expect(screen.queryAllByText('test-message-2')).toBeDefined();
});
});

test('getCacheData', async () => {
network.mock('GET /items', {
status: 200,
data: { message: 'test-message' },
});

// Populate the cache.
const screen1 = render(() => {
const query = useAPIQuery('GET /items', { filter: 'test-filter' });
return <>{query.status}</>;
});

await TestingLibrary.waitFor(() => {
screen1.getByText('success');
});

screen1.unmount();

// Now, fetch from the cache.

const screen2 = render(() => {
const cache = useAPICache();

return (
<>
{cache.getCacheData('GET /items', { filter: 'test-filter' })?.message}
</>
);
});

screen2.getByText('test-message');
});

test('getInfiniteCacheData', async () => {
network.mock('GET /list', {
status: 200,
data: { items: [{ message: 'one' }, { message: 'two' }] },
});

// Populate the cache.
const screen1 = render(() => {
const query = useInfiniteAPIQuery('GET /list', { filter: 'test-filter' });
return <>{query.status}</>;
});

await TestingLibrary.waitFor(() => {
screen1.getByText('success');
});

screen1.unmount();

// Now, fetch from the cache.

const screen2 = render(() => {
const cache = useAPICache();

const value = cache.getInfiniteCacheData('GET /list', {
filter: 'test-filter',
});

const messages = value?.pages.flatMap((p) => p.items).map((i) => i.message);

return <>{messages?.join(',')}</>;
});

screen2.getByText('one,two');
});
10 changes: 10 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,16 @@ export type CacheUtils<Endpoints extends RoughEndpoints> = {
payload: RequestPayloadOf<Endpoints, Route>,
updater: CacheUpdate<InfiniteData<Endpoints[Route]['Response']>>,
) => void;

getCacheData: <Route extends keyof Endpoints & string>(
route: Route,
payload: RequestPayloadOf<Endpoints, Route>,
) => Endpoints[Route]['Response'] | undefined;

getInfiniteCacheData: <Route extends keyof Endpoints & string>(
route: Route,
payload: RequestPayloadOf<Endpoints, Route>,
) => InfiniteData<Endpoints[Route]['Response']> | undefined;
};

export type APIQueryHooks<Endpoints extends RoughEndpoints> = {
Expand Down

0 comments on commit d30ba62

Please sign in to comment.