Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
D

data-client

> 前端框架
Open source

Async State Management without the Management. REST, GraphQL, SSE, Websockets

2.0K stars0 likes0 views
WebsiteGitHub

About

Async State Management without the Management. REST, GraphQL, SSE, Websockets

Installation

bash
npm install --save @data-client/react @data-client/rest @data-client/test

For more details, see the Getting Started docs page.

Skills

bash
npx skills add reactive/data-client

Then run skill "data-client-setup"

Usage

Simple TypeScript definition

typescript
class User extends Entity {
  id = '';
  username = '';
}

class Article extends Entity {
  id = '';
  title = '';
  body = '';
  author = User.fromJS();
  createdAt = Temporal.Instant.fromEpochMilliseconds(0);

  static schema = {
    author: User,
    createdAt: Temporal.Instant.from,
  };
}

Create collection of API Endpoints

typescript
const UserResource = resource({
  path: '/users/:id',
  schema: User,
  optimistic: true,
});

const ArticleResource = resource({
  path: '/articles/:id',
  schema: Article,
  searchParams: {} as { author?: string },
  optimistic: true,
  paginationField: 'cursor',
});

One line data binding

typescript
const article = useSuspense(ArticleResource.get, { id });
return (
  <article>
    <h2>
      {article.title} by {article.author.username}
    </h2>
    <p>{article.body}</p>
  </article>
);

Reactive Mutations

typescript
const ctrl = useController();
return (
  <>
    <CreateArticleForm
      onSubmit={article =>
        ctrl.fetch(ArticleResource.getList.push, { id }, article)
      }
    />
    <ProfileForm
      onSubmit={user =>
        ctrl.fetch(UserResource.update, { id: article.author.id }, user)
      }
    />
    <button onClick={() => ctrl.fetch(ArticleResource.delete, { id })}>
      Delete
    </button>
  </>
);

Subscriptions

typescript
const price = useLive(PriceResource.get, { symbol });
return price.value;

Type-safe Imperative Actions

typescript
const ctrl = useController();
await ctrl.fetch(ArticleResource.update, { id }, articleData);
await ctrl.fetchIfStale(ArticleResource.get, { id });
ctrl.expireAll(ArticleResource.getList);
ctrl.invalidate(ArticleResource.get, { id });
ctrl.invalidateAll(ArticleResource.getList);
ctrl.setResponse(ArticleResource.get, { id }, articleData);
ctrl.set(Article, { id }, articleData);

Programmatic queries

typescript
const queryTotalVotes = new Query(
  new Collection([BlogPost]),
  posts => posts.reduce((total, post) => total + post.votes, 0),
);

const totalVotes = useQuery(queryTotalVotes);
const totalVotesForUser = useQuery(queryTotalVotes, { userId });
typescript
const groupTodoByUser = new Query(
  TodoResource.getList.schema,
  todos => Object.groupBy(todos, todo => todo.userId),
);
const todosByUser = useQuery(groupTodoByUser);

Powerful Middlewares

typescript
class LoggingManager implements Manager {
  middleware: Middleware = controller => next => async action => {
    console.log('before', action, controller.getState());
    await next(action);
    console.log('after', action, controller.getState());
  };

  cleanup() {}
}
typescript
class TickerStream implements Manager {
  middleware: Middleware = controller => {
    this.handleMsg = msg => {
      controller.set(Ticker, { id: msg.id }, msg);
    };
    return next => action => next(action);
  };

  init() {
    this.websocket = new WebSocket('wss://ws-feed.myexchange.com');
    this.websocket.onmessage = event => {
      const msg = JSON.parse(event.data);
      this.handleMsg(msg);
    };
  }
  cleanup() {
    this.websocket.close();
  }
}

Integrated data mocking

…

...all typed ...fast ...and consistent

For the small price of 9kb gziped.    Get started now

Features

  • Strong Typescript inference
  • React Suspense support
  • React 18 Concurrent mode compatible
  • Partial Hydration Server Side Rendering
  • Declarative API
  • Composition over configuration
  • Normalized caching
  • Tiny bundle footprint
  • Automatic overfetching elimination
  • ✨ Fast optimistic updates
  • Flexible to fit any API design (one size fits all)
  • Debugging and inspection via browser extension
  • Tree-shakable (only use what you need)
  • Subscriptions
  • ♻️ Optional redux integration
  • Storybook mocking
  • React Native support
  • Expo support
  • ⚛️ NextJS support
  • Declarative cache lifetime policy
  • Composable middlewares
  • Global data consistency guarantees
  • Automatic race condition elimination
  • Global referential equality guarantees

Examples

  • Todo: | |
  • Github: |
  • NextJS: | |
  • Websockets: | |

API

Reactive Applications

  • Rendering: useSuspense(), useLive(), useCache(), useDLE(), useQuery(), useLoading(), useDebounce(), useCancelling()

  • Event handling: useController() returns Controller

    Method Subject
    Fetch
    ctrl.fetch Endpoint + Args
    ctrl.fetchIfStale Endpoint + Args
    Expiry
    ctrl.expireAll Endpoint
    ctrl.invalidate Endpoint + Args
    ctrl.invalidateAll Endpoint
    ctrl.resetEntireStore Everything
    Set
    ctrl.set Schema + Args
    ctrl.setResponse Endpoint + Args
    ctrl.setError Endpoint + Args
    ctrl.resolve Endpoint + Args
    Subscription
    ctrl.subscribe Endpoint + Args
    ctrl.unsubscribe Endpoint + Args
  • Components: <DataProvider/>, <AsyncBoundary/>, <ErrorBoundary/>, <MockResolver/>

  • Data Mocking: Fixture, Interceptor, renderDataHook()

  • Middleware: LogoutManager, NetworkManager, SubscriptionManager, PollingSubscription, DevToolsManager

Define Data

Networking definition

  • Endpoints: RestEndpoint, GQLEndpoint
  • Resources: resource(), hookifyResource()
Data model
Data Type Mutable Schema Description Queryable
Object ✅ Entity, EntityMixin single unique object ✅
✅ Union(Entity) polymorphic objects (A | B) ✅
Object statically known keys
Inval

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

TypeScriptexpofetchhooksnormalized

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category前端框架
PricingOpen source

> Related tools

R
React
用于构建用户界面的 JavaScript 库
V
Vue.js
渐进式 JavaScript 框架
N
Next.js
基于 React 的全栈 Web 框架