Skip to main content

One post tagged with "http"

View All Tags

· 6 min read
Nathaniel Tucker

Today we're releasing @rest-hooks/rest version 6. While this is a pretty radical departure from previous versions, there is no need to upgrade if previous versions are working as they will continue to work with the current 6.4 release of Rest Hooks as well as many future versions.

First, we have completely decoupled the networking lifecycle RestEndpoint from the data lifecycle Schema. Collections of Endpoints that operate on the same data can be consgtructed by calling createResource.

RestEndpoint

import { RestEndpoint } from '@rest-hooks/rest';
export const getTodo = new RestEndpoint({
urlPrefix: 'https://jsonplaceholder.typicode.com',
path: '/todos/:id',
});
import { useSuspense } from 'rest-hooks';
import { getTodo } from './api/getTodo';
function TodoDetail({ id }: { id: number }) {
const todo = useSuspense(getTodo, { id });
return <div>{todo.title}</div>;
}
render(<TodoDetail id={1} />);
Live Preview
Loading...
Store

The new RestEndpoint optimizes configuration based around HTTP networking. Urls are constructed based on simple named parameters, which are enforced with strict TypeScript automatically.

createResource

import { Entity, createResource } from '@rest-hooks/rest';
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',
schema: Todo,
});
import { useSuspense } from 'rest-hooks';
import { TodoResource } from './api/Todo';
function TodoDetail({ id }: { id: number }) {
const todo = useSuspense(TodoResource.get, { id });
return <div>{todo.title}</div>;
}
render(<TodoDetail id={1} />);
Live Preview
Loading...
Store

createResource creates a simple collection of RestEndpoints. These can be easily overidden, removed as appropriate - or not used altogether. createResource is intended as a quick start point and as a guide to best practices for API interface ergonomics. It is expected to extend or replace createResource based on the common patterns for your own API.

const todo = useSuspense(TodoResource.get, { id: '5' });
const todos = useSuspense(TodoResource.getList);
controller.fetch(TodoResource.create, { content: 'ntucker' });
controller.fetch(TodoResource.update, { id: '5' }, { content: 'ntucker' });
controller.fetch(
TodoResource.partialUpdate,
{ id: '5' },
{ content: 'ntucker' },
);
controller.fetch(TodoResource.delete, { id: '5' });