useCache()
- Type
- With Generics
function useCache(
endpoint: ReadEndpoint,
...args: Parameters<typeof endpoint> | [null]
): Denormalize<typeof endpoint.schema> | null;
function useCache<
E extends Pick<
EndpointInterface<FetchFunction, Schema | undefined, undefined>,
'key' | 'schema' | 'invalidIfStale'
>,
Args extends readonly [...Parameters<E['key']>] | readonly [null],
>(endpoint: E, ...args: Args): DenormalizeNullable<E['schema']>;
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 Endpoint
s to send
Resource provides these built-in:
Feel free to add your own RestEndpoint as well.
Query arbitrary Entities
Query provides programmatic access to the Rest Hooks store.
Fixtures
GET /users
[{"id":"123","name":"Jim"},{"id":"456","name":"Jane"},{"id":"777","name":"Albatras","isAdmin":true}]
▶api/User.ts
▶UsersPage.tsx
import { Query, schema } from '@rest-hooks/rest';import { UserResource, User } from './api/User';const sortedUsers = new Query(new schema.All(User),(entries, { asc } = { asc: false }) => {const sorted = [...entries].sort((a, b) => a.name.localeCompare(b.name));if (asc) return sorted;return sorted.reverse();});function UsersPage() {useFetch(UserResource.getList);const users = useCache(sortedUsers, { asc: true });if (!users) return <div>No users in cache yet</div>;return (<div>{users.map(user => (<div key={user.pk()}>{user.name}</div>))}</div>);}render(<UsersPage />);