Skip to main content

Reactive Data Client

Async State Management without the Management

Share server data and
update it instantly

Reactive Mutations

Render data with useSuspense(). Then mutate with Controller.fetch().

This updates all usages atomically and immediately with zero additional fetches. Rest Hooks automatically ensures data consistency and integrity globally including even the most challenging race conditions.

Editor
import { Entity } from '@data-client/rest';
import { createResource } from '@data-client/rest/next';
export class Post extends Entity {
id = 0;
userId = 0;
title = '';
body = '';
pk() {
return `${this.id}`;
}
}
export const PostResource = createResource({
urlPrefix: 'https://jsonplaceholder.typicode.com',
path: '/posts/:id',
schema: Post,
searchParams: {} as { userId?: string | number } | undefined,
optimistic: true,
});
export class User extends Entity {
id = 0;
name = '';
username = '';
email = '';
phone = '';
website = '';
get profileImage() {
return `https://i.pravatar.cc/256?img=${this.id + 4}`;
}
pk() {
return `${this.id}`;
}
}
export const UserResource = createResource({
urlPrefix: 'https://jsonplaceholder.typicode.com',
path: '/users/:id',
schema: User,
optimistic: true,
});
import { UserResource, type Post } from './resources';
export default function PostItem({ post }: { post: Post }) {
const author = useSuspense(UserResource.get, { id: post.userId });
return (
<div
style={{
display: 'flex',
gap: '1em',
marginBottom: '10px',
}}
>
<Avatar src={author.profileImage} />
<div>
<h4>{post.title}</h4>
<small>by {author.name}</small>
</div>
</div>
);
}
import { UserResource } from './resources';
export default function ProfileEdit({ userId }: { userId: number }) {
const user = useSuspense(UserResource.get, { id: userId });
const controller = useController();
const handleChange = e =>
controller.fetch(
UserResource.partialUpdate,
{ id: userId },
{ name: e.currentTarget.value },
);
return (
<div>
<label>
Name:{' '}
<input
type="text"
value={user.name}
onChange={handleChange}
/>
</label>
</div>
);
}
import PostItem from './PostItem';
import ProfileEdit from './ProfileEdit';
import { PostResource } from './resources';
function PostList() {
const userId = 1;
const posts = useSuspense(PostResource.getList, { userId });
return (
<div>
<ProfileEdit userId={userId} />
<br />
{posts.map(post => (
<PostItem key={post.pk()} post={post} />
))}
</div>
);
}
render(<PostList />);
Live Preview
Loading...
Store

Structured data

Data consistency, performance, and typesafety scale even as your data becomes more complex.

Creates and deletes reactively update the correct lists, even when those lists are nested inside other objects.

Model even the most complex data with polymorphic and unbounded object/maps support.

Editor
import { Entity, schema } from '@data-client/rest';
import { createResource } from '@data-client/rest/next';
export class Todo extends Entity {
id = 0;
userId = 0;
title = '';
completed = false;
pk() {
return `${this.id}`;
}
}
export const TodoResource = createResource({
urlPrefix: 'https://jsonplaceholder.typicode.com',
path: '/todos/:id',
searchParams: {} as { userId?: string | number } | undefined,
schema: Todo,
optimistic: true,
});
export class User extends Entity {
id = 0;
name = '';
username = '';
email = '';
website = '';
todos: Todo[] = [];
get profileImage() {
return `https://i.pravatar.cc/256?img=${this.id + 4}`;
}
pk() {
return `${this.id}`;
}
static schema = {
todos: new schema.Collection([Todo], {
nestKey: (parent, key) => ({
userId: parent.id,
}),
}),
};
}
export const UserResource = createResource({
urlPrefix: 'https://jsonplaceholder.typicode.com',
path: '/users/:id',
schema: User,
optimistic: true,
});
import { TodoResource, type Todo } from './resources';
export default function TodoItem({ todo }: { todo: Todo }) {
const controller = useController();
const handleChange = e =>
controller.fetch(
TodoResource.partialUpdate,
{ id: todo.id },
{ completed: e.currentTarget.checked },
);
const handleDelete = () =>
controller.fetch(TodoResource.delete, {
id: todo.id,
});
return (
<div>
<label>
<input
type="checkbox"
checked={todo.completed}
onChange={handleChange}
/>
{todo.completed ? <strike>{todo.title}</strike> : todo.title}
</label>
<CancelButton onClick={handleDelete} />
</div>
);
}
import { v4 as uuid } from 'uuid';
import { TodoResource } from './resources';
export default function NewTodo({ userId }: { userId: number }) {
const controller = useController();
const handleKeyDown = async e => {
if (e.key === 'Enter') {
controller.fetch(TodoResource.create, {
id: randomId(),
userId,
title: e.currentTarget.value,
});
e.currentTarget.value = '';
}
};
return (
<div>
<input type="checkbox" name="new" checked={false} disabled />{' '}
<input type="text" onKeyDown={handleKeyDown} />
</div>
);
}
function randomId() {
return Number.parseInt(uuid().slice(0, 8), 16);
}
import NewTodo from './NewTodo';
import { type Todo } from './resources';
import TodoItem from './TodoItem';
export default function TodoList({
todos,
userId,
}: {
todos: Todo[];
userId: number;
}) {
return (
<div>
{todos.map(todo => (
<TodoItem key={todo.pk()} todo={todo} />
))}
<NewTodo userId={userId} />
</div>
);
}
import { UserResource } from './resources';
import TodoList from './TodoList';
function UserList() {
const users = useSuspense(UserResource.getList);
return (
<div>
{users.map(user => (
<section key={user.pk()}>
<h4>{user.name}&apos;s tasks</h4>
<TodoList todos={user.todos} userId={user.id} />
</section>
))}
</div>
);
}
render(<UserList />);
Live Preview
Loading...
Store
Editor
import {
GQLEndpoint,
GQLEntity,
Query,
schema,
} from '@data-client/graphql';
const gql = new GQLEndpoint('/');
export class Todo extends GQLEntity {
readonly title: string = '';
readonly completed: boolean = false;
readonly userId: number = 0;
}
export const TodoResource = {
get: gql.query(
`query GetTodo($id: ID!) {
todo(id: $id) {
id
title
completed
userId
}
}
`,
{ todo: Todo },
),
getList: gql.query(
`query GetTodos {
todo {
id
title
completed
userId
}
}
`,
{ todos: [Todo] },
),
update: gql.mutation(
`mutation UpdateTodo($todo: Todo!) {
updateTodo(todo: $todo) {
id
title
completed
}
}`,
{ updateTodo: Todo },
),
queryRemaining: new Query(
new schema.All(Todo),
(entries, { userId } = {}) => {
if (userId !== undefined)
return entries.filter(
todo => todo.userId === userId && !todo.completed,
).length;
return entries.filter(todo => !todo.completed).length;
},
),
};
import { TodoResource, type Todo } from './api';
export default function TodoItem({ todo }: { todo: Todo }) {
const controller = useController();
return (
<div>
<label>
<input
type="checkbox"
checked={todo.completed}
onChange={e =>
controller.fetch(TodoResource.update, {
todo: { id: todo.id, completed: e.currentTarget.checked },
})
}
/>
{todo.completed ? <strike>{todo.title}</strike> : todo.title}
</label>
</div>
);
}
import { useCache } from '@data-client/react';
import { TodoResource } from './api';
export default function TodoStats({ userId }: { userId?: number }) {
const remaining = useCache(TodoResource.queryRemaining, { userId });
return (
<div style={{ textAlign: 'center' }}>
{remaining} tasks remaining
</div>
);
}
import { TodoResource } from './api';
import TodoItem from './TodoItem';
import TodoStats from './TodoStats';
function TodoList() {
const { todos } = useSuspense(TodoResource.getList, {});
return (
<div>
<TodoStats />
{todos.map(todo => (
<TodoItem key={todo.pk()} todo={todo} />
))}
</div>
);
}
render(<TodoList />);
Live Preview
Loading...
Store

Live updates

Keep remote changes in sync with useLive().

Polling, SSE and Websocket or support a custom protocol with middlewares

Editor
import { Entity, schema } from '@data-client/rest';
import { RestEndpoint } from '@data-client/rest/next';
export class ExchangeRates extends Entity {
currency = 'USD';
rates: Record<string, number> = {};
pk(): string {
return this.currency;
}
static schema = {
rates: new schema.Values(FloatSerializer),
};
}
export const getExchangeRates = new RestEndpoint({
urlPrefix: 'https://www.coinbase.com/api/v2',
path: '/exchange-rates',
searchParams: {} as { currency: string },
schema: { data: ExchangeRates },
// in ms; this api does not update the value at a faster rate
pollFrequency: 15000,
});
import { useLive } from '@data-client/react';
import { getExchangeRates } from './resources';
function AssetPrice() {
const { data: price } = useLive(getExchangeRates, {
currency: 'USD',
});
return (
<center>
{assets.map(symbol => (
<div key={symbol}>
{symbol}{' '}
<Formatted
value={1 / price.rates[symbol]}
formatter="currency"
/>
</div>
))}
<br />
<small>Updates every 15 seconds</small>
</center>
);
}
const assets = ['BTC', 'ETH', 'DOGE'];
render(<AssetPrice />);
Live Preview
Loading...
Store
Data IntegrityData Integrity

Data Integrity

Strong inferred types; single source of truth that is referentially stable ensures consistency; asynchronous invariants make it easy to avoid race conditions

Performance

Normalized cache means data is often ready before it is even needed. Automatic request deduplication means less data to send over the network.

Composition over configuration

Declare what you need where you need it. Share data definitions across platforms, components, protocols, and behaviors.

Incremental Adoption

Get started fast with one line data definition and one line data binding. Then add TypeScript, normalized cache with Schemas, optimistic updates and more.