Skip to main content
Version: 6.4

useCache()

function useCache(
endpoint: ReadEndpoint,
...args: Parameters<typeof endpoint> | [null]
): Denormalize<typeof endpoint.schema> | null;

Excellent to use data in the normalized cache without fetching.

  • On Error (404, 500, etc):
    • Returns previously cached if exists
    • null otherwise
  • While loading:
    • Returns previously cached if exists
    • null otherwise

Example

Using a type guard to deal with null

function Post({ id }: { id: number }) {
const post = useCache(PostResource.get, { id });
// post as PostResource | null
if (!post) return null;
// post as PostResource (typeguarded)
// ...render stuff here
}

Paginated data

When entities are stored in nested structures, that structure will remain.

export class PaginatedPost extends Entity {
readonly id: number | null = null;
readonly title: string = '';
readonly content: string = '';

pk() {
return this.id;
}
}

export const getPosts = new RestEndpoint({
path: '/post\\?page=:page',
schema: { results: [PaginatedPost], nextPage: '', lastPage: '' },
});
function ArticleList({ page }: { page: string }) {
const { results: posts, nextPage, lastPage } = useCache(getPosts, { page });
// posts as PaginatedPost[] | null
if (!posts) return null;
// posts as PaginatedPost[] (typeguarded)
// ...render stuff here
}
Conditional Dependencies

Use null as the second argument on any rest hooks to indicate "do nothing."

// todo could be undefined if id is undefined
const todo = useCache(getTodo, id ? { id } : null);

Useful Endpoints to send

Resource provides these built-in:

Feel free to add your own RestEndpoint as well.