useCache() - Normalized data store access in React
Data rendering without the fetch.
Access any Endpoint's response. If the response does not exist, returns
undefined. This can be used to check for an Endpoint's existance like for authentication.
useCache() is reactive to data mutations; rerendering only when necessary.
import { UserResource } from './UserResource'; import Unauthed from './Unauthed'; import Authorized from './Authorized'; function AuthorizedPage() { const currentUser = useCache(UserResource.current); if (!currentUser) return <Unauthed />; return <Authorized user={currentUser} />; } render(<AuthorizedPage />);
See truthiness narrowing for more information about type handling
| 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 to any Data Client hook means "do nothing."
// todo could be undefined if id is undefined
const todo = useCache(TodoResource.get, id ? { id } : null);
- Type
- With Generics
function useCache(
endpoint: ReadEndpoint,
...args: Parameters<typeof endpoint> | [null]
): Denormalize<typeof endpoint.schema> | null;
Github Navbar login/logout
Our current user only exists when we are authenticated. Thus we can useCache(UserResource.current)
to determine whether to show the login or logout navigation buttons.
Here we only show commenting form if the user is authenticated.