REST Usage
- NPM
- Yarn
yarn add @rest-hooks/rest
npm install --save @rest-hooks/rest
This version requires TypeScript 4.0. For older versions, try @rest-hooks/rest@5, which is fully compatible with the latest Rest Hooks clients.
Define the API
RestEndpoint are the methods of your data. Schemas define the data model. Resources are
a collection of endpoints
around one schema
.
- Class
- Mixin
import { Entity, createResource } from '@rest-hooks/rest';import { User } from './User';export class Article extends Entity {id: number | undefined = undefined;title = '';content = '';author = User.fromJS({});tags: string[] = [];createdAt = new Date(0);pk() {return this.id?.toString();}static schema = {author: User,createdAt: Date,};static key = 'Article';}export const ArticleResource = createResource({urlPrefix: 'http://test.com',path: '/article/:id',schema: Article,});
import { schema, createResource } from '@rest-hooks/rest';import { UserEntity } from './User';export class Article {id: number | undefined = undefined;title = '';content = '';author = UserEntity.fromJS({});tags: string[] = [];createdAt = new Date(0);}export class ArticleEntity extends schema.Entity(Article, {schema: {author: UserEntity,createdAt: Date,},key: 'Article',}) {}export const ArticleResource = createResource({urlPrefix: 'http://test.com',path: '/article/:id',schema: ArticleEntity,});
Entity is a kind of schema that has a primary key (pk). This is what allows us to avoid state duplication, which is one of the core design choices that enable such high safety and performance characteristics.
static schema lets us specify declarative transformations like auto field deserialization with createdAt
and nesting the author field.
Urls are constructed by combining the urlPrefix with path templating.
TypeScript enforces the arguments specified with a prefixed colon like :id
in this example.
// GET http://test.com/article/5
TodoResource.get({ id: 5 });
Bind the data with Suspense
- Single
- List
import { useSuspense } from '@rest-hooks/react';
import { ArticleResource } from 'api/article';
export default function ArticleDetail({ id }: { id: number }) {
const article = useSuspense(ArticleResource.get, { id });
return (
<article>
<h2>{article.title}</h2>
<div>{article.content}</div>
</article>
);
}
import { useSuspense } from '@rest-hooks/react';
import { ArticleResource } from 'api/article';
import ArticleSummary from './ArticleSummary';
export default function ArticleList() {
const articles = useSuspense(ArticleResource.getList);
return (
<section>
{articles.map(article => (
<ArticleSummary key={article.pk()} article={article} />
))}
</section>
);
}
useSuspense() acts like await, ensuring the data is available before returning. Learn how to be declare your data dependencies
Mutate the data
- Create
- Update
- Delete
import { useController } from '@rest-hooks/react';
import { ArticleResource } from 'api/article';
export default function NewArticleForm() {
const ctrl = useController();
return (
<Form
onSubmit={e => ctrl.fetch(ArticleResource.create, new FormData(e.target))}
>
<FormField name="title" />
<FormField name="content" type="textarea" />
<FormField name="tags" type="tag" />
</Form>
);
}
create then takes any keyable
body to send as the payload and then returns a promise that
resolves to the new Resource created by the API. It will automatically be added in the cache for any consumers to display.
import { useController } from '@rest-hooks/react';
import { ArticleResource } from 'api/article';
export default function UpdateArticleForm({ id }: { id: number }) {
const article = useSuspense(ArticleResource.get, { id });
const ctrl = useController();
return (
<Form
onSubmit={e =>
ctrl.fetch(ArticleResource.update, { id }, new FormData(e.target))
}
initialValues={article}
>
<FormField name="title" />
<FormField name="content" type="textarea" />
<FormField name="tags" type="tag" />
</Form>
);
}
update then takes any keyable
body to send as the payload and then returns a promise that
then takes any keyable
body to send as the payload and then returns a promise that
resolves to the new Resource created by the API. It will automatically be added in the cache for any consumers to display.
import { useController } from '@rest-hooks/react';
import { Article, ArticleResource } from 'api/article';
export default function ArticleWithDelete({ article }: { article: Article }) {
const ctrl = useController();
return (
<article>
<h2>{article.title}</h2>
<div>{article.content}</div>
<button
onClick={() => ctrl.fetch(ArticleResource.delete, { id: article.id })}
>
Delete
</button>
</article>
);
}
We use FormData in the example since it doesn't require any opinionated form state management solution. Feel free to use whichever one you prefer.
Mutations automatically updates all usages without the need for additional requests.