Skip to main content

useCache()

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.

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 StatusReturnsConditions
Invalidundefinednot in store, deletion, invalidation, invalidIfStale
Staledenormalized(first-render, arg change) & expiry < now
Validdenormalizedfetch completion
undefinednull 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,
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 or refs (including computed); the result updates when they change.