Currently, I am working on integrating swr into my project to create a custom block hook using generics. The goal is to have this hook creator accept mapParamsToKey and request methods as parameters and generate an SWR hook function. However, there seems to be an issue with the return type of my custom hook, SWRResponse, which is not matching the expected type. Below is a snippet of the code I have written for reference.
import useSWR from 'swr';
type Params = {
id: number;
};
type BlogPost = {
id: number;
title: string;
};
const mapParamsToKey = (params: Params) => ['blog-post', params.id];
const request = (params: Params): Promise<BlogPost> => {
const data = { id: params.id, title: `Blog Post ${params.id}` };
return Promise.resolve(data);
};
const useBlogPost = (params: Params) =>
useSWR(mapParamsToKey(params), () => request(params));
// (params: Params) => SWRResponse<BlogPost, any, any>
// swr hooks creator
function createBlockHook<P, T = any>(config: {
mapParamsToKey: (params: P) => Array<string | number>;
request: (params: P) => Promise<T>;
}) {
return (params: P) =>
useSWR(config.mapParamsToKey(params), () => config.request(params));
}
const useBlogPost2 = createBlockHook<Params>({
mapParamsToKey,
request,
});
// (params: Params) => SWRResponse<any, any, any>
// SWRResponse data type is any, but `BlogPost` is expected (infer from `request` param)
Here is how the hook should ideally be used:
import client from './my-api-client';
type CommentParams = { id: number; }
const useComment = createBlockHook<CommentParams>({
mapParamsToKey: (params) => ['comment', params.id],
request: client.getComment, // (params: CommentParams) => Promise<Comment>
});
function Comment(props: { id: number }) {
const swr = useComment(props);
if (swr.data) {
// swr.data with type hint `Comment`
return (
<div>{swr.data.content}</div>
)
}
return <div>...</div>;
}