/rest-hooks

Normalized state management for async data. Safe. Fast. Reusable.

Primary LanguageTypeScriptApache License 2.0Apache-2.0

๐Ÿ›Œ๐ŸŽฃ Rest hooks

CircleCI Coverage Status npm downloads bundle size npm version PRs Welcome Chat

Define your async methods. Use them synchronously in React. Instantly mutate the data and automatically update all usages.

For REST, GraphQL, Websockets+SSE and more

๐ŸŒŽ Website

๐Ÿ“–Read The Docs  |  ๐ŸGetting Started  |  ๐ŸŽฎTodo Demo  |  ๐ŸŽฎGithub Demo  |  ๐ŸŽฎNextJS SSR Demo

Installation

npm install @rest-hooks/react @rest-hooks/rest @rest-hooks/test

For more details, see the Installation docs page.

Usage

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

  pk() {
    return this.id;
  }
}

class Article extends Entity {
  id = '';
  title = '';
  body = '';
  author = User.fromJS();

  pk() {
    return this.id;
  }

  static schema = {
    author: User,
  }
}
const UserResource = createResource({
  path: '/users/:id',
  schema: User,
});

const ArticleResource = createResource({
  path: '/articles/:id',
  schema: Article,
});

One line data binding

const article = useSuspense(ArticleResource.get, { id });
return (
  <>
    <h2>{article.title} by {article.author.username}</h2>
    <p>{article.body}</p>
  </>
);
const ctrl = useController();
return (
  <ProfileForm
    onSubmit={data => ctrl.fetch(UserResource.update, { id }, data)}
  />
);
const price = useLive(PriceResource.get, { symbol });
return price.value;
const sortedArticles = new Query(
  new schema.All(Article),
  (entries, { asc } = { asc: false }) => {
    const sorted = [...entries].sort((a, b) => a.title.localeCompare(b.title));
    if (asc) return sorted;
    return sorted.reverse();
  }
);

const articlesUnsorted = useCache(sortedArticles);
const articlesAscending = useCache(sortedArticles, { asc: true });
const articlesDescending = useCache(sortedArticles, { asc: false });

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

For the small price of 9kb gziped.    ๐ŸGet started now | ๐ŸฅŠComparison

Features

Examples