useCache()
Data rendering without the fetch.
General purpose store access can be useful when the data's existance is of interest (like if a user is authenticated), or general purpose store access like Query.
useCache()
will rerender when its data mutates.
Usage
UserResource
Unauthed
Authorized
Entry
import { UserResource } from './UserResource'; import Unauthed from './Unauthed'; import Authorized from './Authorized'; function AuthorizedPage() { // currentUser as User | undefined const currentUser = useCache(UserResource.current); // user is not logged in if (!currentUser) return <Unauthed />; // currentUser as User (typeguarded) return <Authorized user={currentUser} />; } render(<AuthorizedPage />);
🔴 Live Preview
Store▶
See truthiness narrowing for more information about type handling
Behavior
Expiry Status | Returns | Conditions |
---|---|---|
Invalid | undefined | not in store, deletion, invalidation, invalidIfStale |
Stale | denormalized | (first-render, arg change) & expiry < now |
Valid | denormalized | fetch completion |
undefined | null used as second argument |
Conditional Dependencies
Use null
as the second argument on any reactive data client to indicate "do nothing."
// todo could be undefined if id is undefined
const todo = useCache(TodoResource.get, id ? { id } : null);
Types
- 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']>;
Examples
Query arbitrary Entities
Query provides programmatic access to the Reactive Data Client store.
UserResource
UsersPage
import { Query, schema } from '@data-client/rest'; import { UserResource, User } from './UserResource'; 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 />);
🔴 Live Preview
Store▶