useCache()
Data rendering without the fetch.
Access any Endpoint's response. Returns undefined until it is fetched, set, or
inferable from entities already in the store, and again after invalidation (see Behavior).
That means "not loaded", not "doesn't exist on the server", so use it for data other code loads, like
the current user a login flow fetches.
useCache() is reactive to data mutations; rerendering only when necessary.
Usage
<script setup lang="ts"> import { useCache } from '@data-client/vue'; import { UserResource } from './UserResource'; import Unauthed from './Unauthed.vue'; import Authorized from './Authorized.vue'; // currentUser as ComputedRef<User | undefined> const currentUser = useCache(UserResource.current); </script> <template> <!-- currentUser is unwrapped in the template --> <Authorized v-if="currentUser" :user="currentUser" /> <!-- user is not logged in --> <Unauthed v-else /> </template>
See truthiness narrowing for more information about type handling
Behavior
useCache() returns a ComputedRef. The table
below describes its .value.
| 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 |
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,
computed(() => (id.value ? { id: id.value } : null)),
);
Types
function useCache(
endpoint: ReadEndpoint,
...args: MaybeRefsOrGetters<Parameters<typeof endpoint.key>> | [null]
): ComputedRef<DenormalizeNullable<typeof endpoint.schema>>;
Arguments can be plain values, refs (including computed), or getter
functions like () => ({ id: props.id }). A plain object like { id: props.id } is read once and won't
follow prop or route changes, so use a getter or computed when an argument can change.
The result updates when the arguments change.