reactive/data-client / .agents/skills/data-client-react
data-client-react
UnverifiedRead, change and render async and shared state in React with @data-client/react: any data from an API or other async source, and global state shared across components (it has to persist somewhere, which makes it async). Use it for loading and error states, mutations and forms, filtered or derived views, and debugging data that looks wrong or stale on screen. Use it in place of fetch in useEffect, or app-wide useState and context; its main hooks are useSuspense, useQuery and useController.
references/useCache.md
View on GitHub<!-- Generated by `yarn build:skills` from docs/core/api/useCache.md (react). Edit the source doc, not this file. -->
# useCache()
Data rendering without the fetch.
Access any [Endpoint](https://dataclient.io/rest/api/Endpoint)'s response. Returns `undefined` until it is fetched, set, or
inferable from entities already in the store, and again after invalidation (see [Behavior](#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](./mutations.md); rerendering only when necessary.
## Usage
```ts title="UserResource"
import { Entity, resource } from '@data-client/rest';
export class User extends Entity {
id = '';
name = '';
isAdmin = false;
static key = 'User';
}
export const UserResource = resource({
path: '/users/:id',
schema: User,
}).extend('current', {
path: '/user',
schema: User,
});
```
```tsx title="Unauthed"
import { useController, useLoading } from '@data-client/react';
import { UserResource } from './UserResource';
export default function Unauthed() {
const ctrl = useController();
const [handleLogin, loading] = useLoading(
(e: any) => ctrl.fetch(UserResource.current),
[],
);
return (
<div>
<p>Not authorized</p>
{loading ? (
'logging in...'
) : (
<button onClick={handleLogin}>Login</button>
)}
</div>
);
}
```
```tsx title="Authorized"
import { useController } from '@data-client/react';
import { User, UserResource } from './UserResource';
export default function Authorized({ user }: { user: User }) {
const ctrl = useController();
const handleLogout = (e: any) => ctrl.invalidate(UserResource.current);
return (
<div>
<p>Welcome, {user.name}!</p>
<button onClick={handleLogout}>Logout</button>
</div>
);
}
```
```tsx title="Entry" {8}
import { useCache } from '@data-client/react';
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 />);
```
See [truthiness narrowing](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#truthiness-narrowing) for
more information about type handling
## Behavior
| Expiry Status | Returns | Conditions |
| ------------- | ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Invalid | `undefined` | not in store, [deletion](https://dataclient.io/rest/api/resource#delete), [invalidation](./Controller.md#invalidate), [invalidIfStale](https://dataclient.io/docs/concepts/expiry-policy#endpointinvalidifstale) |
| Stale | denormalized | (first-render, arg change) & [expiry < now](https://dataclient.io/docs/concepts/expiry-policy) |
| Valid | denormalized | fetch completion |
| | `undefined` | `null` used as second argument |
> **Tip: Conditional Dependencies**
>
> Use `null` as the second argument to any Data Client hook means "do nothing."
> A [RestEndpoint](https://dataclient.io/rest/api/RestEndpoint) without path or search params takes `{}` in its place, like `enabled ? {} : null`.
>
> ```typescript
> // todo could be undefined if id is undefined
> const todo = useCache(TodoResource.get, id ? { id } : null);
> ```
## Types
```typescript
function useCache(
endpoint: ReadEndpoint,
...args: Parameters<typeof endpoint> | [null]
): Denormalize<typeof endpoint.schema> | null;
```
```typescript
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
### 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.
Example app: [github-app](https://github.com/reactive/data-client/tree/master/examples/github-app) ([`src/resources/User.ts`](https://github.com/reactive/data-client/blob/master/examples/github-app/src/resources/User.ts), [`src/navigation/NavBar.tsx`](https://github.com/reactive/data-client/blob/master/examples/github-app/src/navigation/NavBar.tsx))
### Github Comment Authorization
Here we only show commenting form if the user is authenticated.
Example app: [github-app](https://github.com/reactive/data-client/tree/master/examples/github-app) ([`src/resources/User.ts`](https://github.com/reactive/data-client/blob/master/examples/github-app/src/resources/User.ts), [`src/pages/IssueDetail/CreateComment.tsx`](https://github.com/reactive/data-client/blob/master/examples/github-app/src/pages/IssueDetail/CreateComment.tsx))
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| brainstormingobra/superpowersYou MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or planning anything new, in software or out of it (a talk, a business, a renovation). | Stars: 319k | Updated | Claude CodeCodex | Verified | Install |
| brand-guidelinesanthropics/skillsApplies Anthropic's official brand colors and typography to any sort of artifact that may benefit from having Anthropic's look-and-feel. Use it when brand colors or style guidelines, visual formatting, or company design standards apply. | Stars: 196k | Updated | Claude CodeCodex | Verified | Install |
| frontend-designanthropics/skillsGuidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults. | Stars: 196k | Updated | Claude CodeCodex | Verified | Install |
| mcp-builderanthropics/skillsGuide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK). | Stars: 196k | Updated | Claude CodeCodex | Verified | Install |