问题描述
在 Apollo Client v3
React 实现中,我使用钩子来使用订阅.当我从订阅接收数据时,我想重新获取查询,但前提是查询先前已执行且在缓存中.有没有办法做到这一点?
In Apollo Client v3
React implementation, I am using hooks to use subscription. When I receive data from subscription I would like to refetch query but only if query has been previously executed and is in cache. Is there a way to achieve this?
我首先进行延迟查询,然后在收到订阅数据时手动检查缓存,然后尝试执行延迟查询并重新获取.它有效,但感觉很笨重...
I have started by having a lazy query and then checking the cache manually when subscription data received and then trying to execute lazy query and refetch. It works but it just feels clunky...
export const useMyStuffLazyRefetch = () => {
const [refetchNeeded, setRefetchNeeded] = useState<boolean>(false);
const client = useApolloClient();
const [getMyStuff, { data, refetch }] = useLazyQuery<IStuffData>(GET_MY_STUFF);
useEffect(() => {
if (refetchNeeded) {
setRefetchNeeded(false);
refetch();
}
}, [refetchNeeded]);
const refetchIfNeeded = async () => {
const stuffData = client.cache.readQuery<IStuffData>({ query: GET_MY_STUFF });
if (!stuffData?.myStuff?.length) return;
getMyStuff();
setRefetchNeeded(true);
}
return {
refetchIfNeeded: refetchIfNeeded
};
}
推荐答案
如果这对某人有帮助.我创建了一个单独的钩子,这样使用起来就不那么碍眼了.
In case this can help to somebody. I have created a separate hook so the usage is less of an eyesore.
如果数据在缓存中,这是重新获取的钩子.如果数据不在缓存中,Apollo Client
会出错,而不是返回类似 undefined
或 null
This is the hook to refetch if data is in cache. If the data is not in the cache, Apollo Client
errors instead of returning something like undefined
or null
import { useState, useEffect } from "react";
import { OperationVariables, DocumentNode, LazyQueryHookOptions, useApolloClient, useLazyQuery } from "@apollo/client";
export default function useLazyRefetch <TData = any, TVariables = OperationVariables>(query: DocumentNode, options?: LazyQueryHookOptions<TData, TVariables>) {
const [refetchNeeded, setRefetchNeeded] = useState<boolean>(false);
const [loadData, { refetch }] = useLazyQuery(query, options);
const client = useApolloClient();
useEffect(() => {
if (refetchNeeded) {
setRefetchNeeded(false);
refetch();
}
}, [refetchNeeded]);
const refetchIfNeeded = (variables: TVariables) => {
try {
const cachecData = client.cache.readQuery<
TData,
TVariables
>({
query: query,
variables: variables
});
if (!cachecData) return;
loadData({ variables: variables });
setRefetchNeeded(true);
}
catch {}
};
return {
refetchIfNeeded: refetchIfNeeded
};
}
以及钩子用法示例:
const { refetchIfNeeded } = useLazyRefetch<
IStuffData,
{ dataId?: string }
>(GET_MY_STUFF);
//... And then you can just call it when you need to
refetchIfNeeded({ dataId: "foo" });
这篇关于Apollo 客户端延迟重新获取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!