[英]Does swr useSWR hook have to send HTTP request for revalidation every time the data is used even though cached data exist?
[英]SWR, creating a wrapper around the useSWR hook to show loading state
我在 React.js 应用程序中使用SWR ,我发现自己需要显示请求的加载状态。
我创建了一个辅助函数,它从SWRResponse
中提取加载状态,类似于 SWR 在其文档示例中提供的内容:
const isLoading = ({ data, error }: SWRResponse<any, any>): boolean => {
return data === undefined && error === undefined;
}
我想创建一个包装钩子,它总是在返回值中添加这个信息,类似于以下内容:
const useSWRWithLoading: SWRHook = (...args) => {
const swrResponse = useSWR(...args);
return { ...swrResponse, isLoading: isLoading(swrResponse) };
};
因为我使用了内置类型SWRHook
,所以我不支持isLoading
值。
const useSWRWithLoading = (...args: Parameters<SWRHook>): ReturnType<SWRHook> & { isLoading: boolean } => {
const swrResponse = useSWR(...args);
return { ...swrResponse, isLoading: isLoading(swrResponse) };
};
或(这与以前几乎相同)
type SWRHookWithLoading = (...args: Parameters<SWRHook>) => ReturnType<SWRHook> & { isLoading: boolean };
const useSWRWithLoading: SWRHookWithLoading = (...args) => {
const swrResponse = useSWR(...args);
return { ...swrResponse, isLoading: isLoading(swrResponse) };
};
我注意到的一件事是:
type Foo = Parameters<SWRHook>; // type Foo = never
type Bar = ReturnType<SWRHook>; // type Bar = SWRResponse<unknown,unknown>
而且我不知道如何解决它。
如果我尝试将SWRHookWithLoading
类型设为泛型,我会收到一条错误消息: Type 'SWRHook' is not generic.
.
type SWRHookWithLoading<Data = any, Error = any> = (...args: Parameters<SWRHook<Data, Error>>) => ReturnType<SWRHook<Data, Error>> & { isLoading: boolean };
这让我很困惑,因为SWRHook
的类型定义是:
export declare type SWRHook = <Data = any, Error = any>(...args: readonly [Key] | readonly [Key, Fetcher<Data> | null] | readonly [Key, SWRConfiguration<Data, Error> | undefined] | readonly [Key, Fetcher<Data> | null, SWRConfiguration<Data, Error> | undefined]) => SWRResponse<Data, Error>;
这对我来说似乎是通用的。
我建议为每个查询创建一个钩子,然后允许您返回自定义值。 在下面的示例中,函数useUser
从useSWR
函数作为user
返回data
属性,以及自定义属性isLoading
和isError
。 isLoading
在没有错误时为真,但也没有数据。 如果有数据、错误或两者兼有,则为假。
function useUser (id) {
const { data, error } = useSWR(`/api/user/${id}`, fetcher)
return {
user: data,
isLoading: !error && !data,
isError: error
}
}
资料来源:SWR 文档
这种方法还可以更轻松地在代码库的各个区域之间共享查询。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.