useResource()
- Type
- With Generics
function useResource(endpoint: ReadEndpoint, params: object | null):
Denormalize<typeof endpoint.schema>;
function useResource(...[endpoint: ReadEndpoint, params: object | null]):
Denormalize<typeof endpoint.schema>[];
function useResource<
Params extends Readonly<object>,
S extends Schema
>(endpoint: ReadEndpoint<(p:Params) => Promise<any>, S>, params: Params | null): Denormalize<S>;
function useResource<
Params extends Readonly<object>,
S extends Schema
>(...[endpoint: ReadEndpoint<(p:Params) => Promise<any>, S>, params: Params | null]): Denormalize<S>[];
Excellent for retrieving the data you need.
useResource()
suspends rendering until the data is available. This is much like awaiting an async function. That is to say, the lines after the function won't be run until resolution (data is available).
Cache policy is Stale-While-Revalidate by default but also configurable.
- Triggers fetch:
- On first-render
- or parameters change
- or required entity is deleted
- or imperative invalidation triggered
- and When not in cache or result is considered stale
- and When no identical requests are in flight
- and when params are not null
- On first-render
- On Error (404, 500, etc):
- Throws error to be caught by Error Boundaries
- While Loading:
- Returns previously cached if exists (even if stale)
- except in case of delete or invalidation
- Suspend rendering otherwise
- Returns previously cached if exists (even if stale)
Single
function Post({ id }: { id: number }) {
const post = useResource(PostResource.detail(), { id });
// post as PostResource
}
List
function Posts() {
const posts = useResource(PostResource.list(), {});
// posts as PostResource[]
}
Parallel
function Posts() {
const [user, posts] = useResource(
[UserResource.detail(), { id: userId }],
[PostResource.list(), { userId }],
);
// user as UserResource
// posts as PostResource[]
}
Sequential
function PostWithAuthor() {
const post = useResource(PostResource.detail(), { id });
// post as PostResource
const author = useResource(UserResource.detail(), {
id: post.userId,
});
// author as UserResource
}
Paginated data
When entities are stored in nested structures, that structure will remain.
export class PaginatedPostResource extends Resource {
readonly id: number | null = null;
readonly title: string = '';
readonly content: string = '';
static urlRoot = 'http://test.com/post/';
static list<T extends typeof Resource>(this: T) {
return super.list().extend({
schema: { results: [this], nextPage: '', lastPage: '' },
});
}
}
function ArticleList({ page }: { page: string }) {
const { results: posts, nextPage, lastPage } = useResource(
PaginatedPostResource.list(),
{ page },
);
// posts as PaginatedPostResource[]
}
Useful Endpoint
s to send
Resource provides these built-in:
- detail()
- list()
Feel free to add your own Endpoint as well.