useCache()
无需 fetch 即可渲染数据。
访问任意 Endpoint 的响应。如果响应不存在,则返回
undefined。这可以用来检查某个 Endpoint's 的响应是否存在,例如用于身份验证。
useCache() 会响应数据变更,仅在必要时重新渲染。
用法
UserResource
Unauthed
Authorized
Entry
import { useCache } from '@data-client/react'; import { UserResource } from './UserResource'; import Unauthed from './Unauthed'; import Authorized from './Authorized'; function AuthorizedPage() { // currentUser as User | undefined const currentUser = useCache(UserResource.current); // user is not logged in if (!currentUser) return <Unauthed />; // currentUser as User (typeguarded) return <Authorized user={currentUser} />; } render(<AuthorizedPage />);
结果
Store▶
有关类型处理的更多信息,请参阅真值收窄
行为
| 过期状态 | 返回值 | 条件 |
|---|---|---|
| 无效 | undefined | 不在 store 中、删除、失效、invalidIfStale |
| 过时 | 反规范化数据 | (首次渲染、参数变化)& 过期时间 < 当前时间 |
| 有效 | 反规范化数据 | fetch 完成 |
undefined | 第二个参数传入 null |
条件依赖
将 null 作为任意 Data Client hook 的第二个参数,表示“什么都不做”。
// todo could be undefined if id is undefined
const todo = useCache(TodoResource.get, id ? { id } : null);
类型
- 类型
- 使用泛型
function useCache(
endpoint: ReadEndpoint,
...args: Parameters<typeof endpoint> | [null]
): Denormalize<typeof endpoint.schema> | null;
function useCache<
E extends Pick<
EndpointInterface<FetchFunction, Schema | undefined, undefined>,
'key' | 'schema' | 'invalidIfStale'
>,
Args extends readonly [...Parameters<E['key']>] | readonly [null],
>(endpoint: E, ...args: Args): DenormalizeNullable<E['schema']>;
示例
Github 导航栏登录/登出
当前用户只有在通过身份验证后才存在。因此我们可以使用 useCache(UserResource.current)
来决定显示登录还是登出导航按钮。
探索 github-app 示例
Github 评论授权
这里我们仅在用户通过身份验证后才显示评论表单。
探索 github-app 示例