Skip to content

reactive/data-client / .agents/skills/data-client-schema

data-client-schema

Verified

Model the app's data with @data-client schemas, which normalize responses into one shared cache so an update shows everywhere. Use it whenever an endpoint returning data is added or its response changes (resource, RestEndpoint, GraphQL, Endpoint), when the data's shape changes, when data from different endpoints must be joined or related, when deriving views from loaded data, or when one item looks different in two places. Covers Entity, GQLEntity, Collection, Union and Query.

FileKindSize
SKILL.mdskill md11.9 KB
evals/evals.jsonconfig17.2 KB
references.jsonconfig1.1 KB
references/All.mdmarkdown5.9 KB
references/All.vue.mdmarkdown6.4 KB
references/Array.mdmarkdown5.3 KB
references/Array.vue.mdmarkdown5.9 KB
references/Collection.mdmarkdown18.9 KB
references/Collection.vue.mdmarkdown18.9 KB
references/Entity.mdmarkdown22.4 KB
references/Entity.vue.mdmarkdown22.3 KB
references/EntityMixin.mdmarkdown13.6 KB
references/EntityMixin.vue.mdmarkdown13.6 KB
references/Invalidate.mdmarkdown6.1 KB
references/Invalidate.vue.mdmarkdown6.1 KB
references/Lazy.mdmarkdown4.6 KB
references/Lazy.vue.mdmarkdown4.7 KB
references/Object.mdmarkdown1.5 KB
references/Object.vue.mdmarkdown1.5 KB
references/Query.mdmarkdown9.9 KB
references/Query.vue.mdmarkdown10.2 KB
references/Scalar.mdmarkdown13.1 KB
references/Scalar.vue.mdmarkdown12.8 KB
references/Union.mdmarkdown4.7 KB
references/Union.vue.mdmarkdown4.7 KB
references/Values.mdmarkdown5.4 KB
references/Values.vue.mdmarkdown5.9 KB
references/_ScalarDemo.mdmarkdown3.6 KB
references/_ScalarDemo.vue.mdmarkdown3.5 KB
references/computed-properties.mdmarkdown9.9 KB
references/computed-properties.vue.mdmarkdown9.9 KB
references/partial-entities.mdmarkdown3.8 KB
references/partial-entities.vue.mdmarkdown3.8 KB
references/relational-data.mdmarkdown16.2 KB
references/relational-data.vue.mdmarkdown15.7 KB
references/schema.mdmarkdown9.5 KB
references/schema.vue.mdmarkdown9.5 KB
references/side-effects.mdmarkdown2.5 KB
references/side-effects.vue.mdmarkdown2.6 KB
references/sorting-client-side.mdmarkdown2.7 KB
references/sorting-client-side.vue.mdmarkdown2.8 KB
references/validation.mdmarkdown4.3 KB
references/validation.vue.mdmarkdown4.3 KB

references/Query.md

View on GitHub
<!-- Generated by `yarn build:skills` from docs/rest/api/Query.md (react). Edit the source doc, not this file. -->

# Query

`Query` provides programmatic access to the Reactive Data Client cache while maintaining
the same high performance and referential equality guarantees expected of Reactive Data Client.

`Query` can be rendered using [schema lookup hook useQuery()](https://dataclient.io/docs/api/useQuery)

## Query members

### schema

[Schema](./schema.md) used to retrieve/denormalize data from the Reactive Data Client cache.
This accepts any [Queryable](./schema.md#queryable) schema: [Entity](./Entity.md), [All](./All.md), [Collection](./Collection.md), [Query](./Query.md),
[Union](./Union.md), [Scalar](./Scalar.md), and [Object](./Object.md) schemas for joining multiple entities.
[Lazy](./Lazy.md) fields produce a Queryable via their [`.query`](./Lazy.md#query) accessor.

### process(entries, ...args) {#process}

Takes the (denormalized) response as entries and arguments and returns the new
response for use with [useQuery](https://dataclient.io/docs/api/useQuery)

`useQuery(query, ...args)` passes every argument to the Query's `schema` and to `process`, after the entries, so
check each argument against both. The schema finds its data with the arguments, as `useQuery(schema, ...args)`
would; when it finds nothing, `useQuery()` returns `undefined`. Give `process` an argument of its own only if the
schema ignores it: [All](./All.md) ignores every argument.

## Usage

### Maintaining sort after creates {#sorting}

```ts title="getPosts" {17-24}
import { Collection, Entity, Query, RestEndpoint } from '@data-client/rest';

export class Post extends Entity {
  id = '';
  title = '';
  group = '';
  author = '';
}

export const getPosts = new RestEndpoint({
  path: '/:group/posts',
  searchParams: {} as { orderBy?: string; author?: string },
  schema: new Query(
    new Collection([Post], {
      nonFilterArgumentKeys: /orderBy/,
    }),
    (posts, { orderBy } = {}) => {
      if (orderBy) {
        return [...posts].sort((a, b) =>
          a[orderBy].localeCompare(b[orderBy]),
        );
      }
      return posts;
    },
  ),
});
```

```tsx title="NewPost"
import { useController, useLoading } from '@data-client/react';
import { getPosts } from './getPosts';

export default function NewPost({ author }: Props) {
  const ctrl = useController();

  const [handlePress, loading] = useLoading(async e => {
    if (e.key === 'Enter') {
      const title = e.currentTarget.value;
      e.currentTarget.value = '';
      await ctrl.fetch(
        getPosts.push,
        { group: 'react' },
        {
          title,
          author,
        },
      );
    }
  });

  return (
    <input
      type="text"
      aria-label="New post title"
      placeholder="Post title"
      aria-busy={loading}
      onKeyDown={handlePress}
    />
  );
}
interface Props {
  author: string;
}
```

```tsx title="PostList" {8}
import { useSuspense } from '@data-client/react';
import { getPosts } from './getPosts';
import NewPost from './NewPost';

export default function PostList({ author }: Props) {
  const posts = useSuspense(getPosts, {
    author,
    orderBy: 'title',
    group: 'react',
  });
  return (
    <div>
      {posts.map(post => (
        <div key={post.pk()}>{post.title}</div>
      ))}
      <NewPost author={author} />
    </div>
  );
}
interface Props {
  author: string;
}
```

```tsx title="UserList"
import PostList from './PostList';

function UserList() {
  const users = ['bob', 'clara'];
  return (
    <div>
      {users.map(user => (
        <section key={user}>
          <h3>{user}</h3>
          <PostList author={user} />
        </section>
      ))}
    </div>
  );
}
render(<UserList />);
```

### Aggregates

```ts title="resources/User"
import { Entity, resource } from '@data-client/rest';

export class User extends Entity {
  id = '';
  name = '';
  isAdmin = false;
}
export const UserResource = resource({
  path: '/users/:id',
  schema: User,
});
```

```tsx title="UsersPage"
import { All, Query } from '@data-client/rest';
import { useQuery, useFetch } from '@data-client/react';
import { UserResource, User } from './resources/User';

const countUsers = new Query(
  new All(User),
  (entries, { isAdmin } = {}) => {
    if (isAdmin !== undefined)
      return entries.filter(user => user.isAdmin === isAdmin).length;
    return entries.length;
  },
);

function UsersPage() {
  useFetch(UserResource.getList);
  const userCount = useQuery(countUsers);
  const adminCount = useQuery(countUsers, { isAdmin: true });
  if (userCount === undefined) return <div>No users in cache yet</div>;
  return (
    <div>
      <div>Total users: {userCount}</div>
      <div>Total admins: {adminCount}</div>
    </div>
  );
}
render(<UsersPage />);
```

### Rearranging data with groupBy aggregations {#groupby}

```ts title="resources/User"
import { Entity, resource } from '@data-client/rest';

export class User extends Entity {
  id = 0;
  username = '';
  name = '';
  email = '';
  website = '';
}
export const UserResource = resource({
  urlPrefix: 'https://jsonplaceholder.typicode.com',
  path: '/users/:id',
  schema: User,
});
```

```ts title="resources/Todo"
import { Entity, resource } from '@data-client/rest';
import { User } from './User';

export class Todo extends Entity {
  id = 0;
  userId = 0;
  user? = User.fromJS({});
  title = '';
  completed = false;

  static schema = {
    user: User,
  };
  static process(input) {
    return { ...input, user: input.userId };
  }
}
export const TodoResource = resource({
  urlPrefix: 'https://jsonplaceholder.typicode.com',
  path: '/todos/:id',
  schema: Todo,
  searchParams: {} as { userId?: string | number } | undefined,
});
```

```tsx title="TodoByUser"
import { useQuery } from '@data-client/react';
import { User } from './resources/User';
import type { Todo } from './resources/Todo';

export default function TodoByUser({ userId, todos }: Props) {
  const user = useQuery(User, { id: userId });
  // don't bother if no user is loaded yet
  if (!user) return null;
  return (
    <div>
      <h3>
        {user.name} has {tasksRemaining(todos)} tasks left
      </h3>
      {todos.slice(0, 3).map(todo => (
        <div key={todo.pk()}>
          {todo.title} by {todo.user === user ? todo.user.name : ''}
        </div>
      ))}
    </div>
  );
}
function tasksRemaining(todos: Todo[]) {
  return todos.filter(({ completed }) => !completed).length;
}
interface Props {
  userId: string;
  todos: Todo[];
}
```

```tsx title="TodoJoined"
import { Query } from '@data-client/rest';
import { useQuery, useFetch, useSuspense } from '@data-client/react';
import { TodoResource } from './resources/Todo';
import { UserResource } from './resources/User';
import TodoByUser from './TodoByUser';

const groupTodoByUser = new Query(
  TodoResource.getList.schema,
  todos => Object.groupBy(todos, todo => todo.userId),
);

function TodosPage() {
  useFetch(UserResource.getList);
  useSuspense(TodoResource.getList);
  useSuspense(UserResource.getList);
  const todosByUser = useQuery(groupTodoByUser);
  if (!todosByUser) return <div>Todos not found</div>;
  return (
    <div>
      {Object.keys(todosByUser).map(userId => (
        <TodoByUser
          key={userId}
          userId={userId}
          todos={todosByUser[userId]}
        />
      ))}
    </div>
  );
}
render(<TodosPage />);
```

### Object Schema Joins {#object-schema-joins}

`Query` can take [Object Schemas](./Object.md), enabling joins across multiple entity types. This allows you to combine data from different entities in a single query.

```ts title="resources/Ticker"
import { Entity, resource } from '@data-client/rest';

export class Ticker extends Entity {
  product_id = '';
  price = 0;
  pk() { return this.product_id; }
}

export const TickerResource = resource({
  path: '/tickers/:product_id',
  schema: Ticker,
});
```

```ts title="resources/Stats"
import { Entity, resource } from '@data-client/rest';

export class Stats extends Entity {
  product_id = '';
  last = 0;
  pk() { return this.product_id; }
}

export const StatsResource = resource({
  path: '/stats/:product_id',
  schema: Stats,
});
```

```tsx title="PriceDisplay"
import { Query } from '@data-client/rest';
import { useQuery, useFetch } from '@data-client/react';
import NumberFlow from '@number-flow/react';
import { TickerResource, Ticker } from './resources/Ticker';
import { StatsResource, Stats } from './resources/Stats';

// Join Ticker and Stats by product_id
const queryPrice = new Query(
  { ticker: Ticker, stats: Stats },
  ({ ticker, stats }) => ticker?.price ?? stats?.last,
);

function PriceDisplay({ productId }: { productId: string }) {
  useFetch(TickerResource.get, { product_id: productId });
  useFetch(StatsResource.get, { product_id: productId });
  const price = useQuery(queryPrice, { product_id: productId });
  
  return (
    <dl className="stats">
      <div>
        <dt>{productId}</dt>
        <dd>
          {price === undefined ?
            <span className="skeleton" />
          : <NumberFlow
              value={price}
              format={{ style: 'currency', currency: 'USD' }}
            />
          }
        </dd>
      </div>
    </dl>
  );
}

render(<PriceDisplay productId="BTC-USD" />);
```

### Fallback joins

In this case `Ticker` is constantly updated from a websocket stream. However, there is no bulk/list
fetch for `Ticker` - making it inefficient for getting the prices on a list view.

So in this case we can fetch a list of `Stats` as a fallback since it has price data as well.

Example app: [coin-app](https://github.com/reactive/data-client/tree/master/examples/coin-app) ([`src/pages/Home/CurrencyList.tsx`](https://github.com/reactive/data-client/blob/master/examples/coin-app/src/pages/Home/CurrencyList.tsx), [`src/pages/Home/AssetPrice.tsx`](https://github.com/reactive/data-client/blob/master/examples/coin-app/src/pages/Home/AssetPrice.tsx), [`src/resources/fallbackQueries.ts`](https://github.com/reactive/data-client/blob/master/examples/coin-app/src/resources/fallbackQueries.ts))
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 196kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 193kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 193kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 193kUpdated Claude CodeCodexVerifiedInstall