[英]Overcome endless looping when executing useQuery (ApolloClient) by defining a new client
我需要在运行“useQuery”时定义“客户端”,但我会无限循环。
我写的代码如下:
const QueryKTP = gql`
query {
documents(transactionId:"${transactionId}", input: [
{documentType:"KTP"}
]){
documentResponses{
documentType
documentBase64
}
responseDescription
responseCode
message
}
}`
const anotherClient = new ApolloClient({
uri: "https://my-url/online-service/graphql"
});
const { data, loading } = useQuery(QueryKTP, {client: anotherClient});
如果我将上面的脚本更改为如下所示(删除新客户端),则不再发生循环。
const { data, loading } = useQuery(QueryKTP);
我需要修复什么? 谢谢
终于,我想通了。 我遇到了同样的问题,我通过从渲染函数中排除new ApolloClient
来解决它。
实际上,我没有从您的代码中看到渲染功能,但就我而言,它是这样的:
前
export default function MyComponent () {
const anotherClient = new ApolloClient({
uri: "https://my-url/online-service/graphql"
});
const { data, loading } = useQuery(QueryKTP, {client: anotherClient});
}
后
const anotherClient = new ApolloClient({
uri: "https://my-url/online-service/graphql"
});
export default function MyComponent () {
const { data, loading } = useQuery(QueryKTP, {client: anotherClient});
}
就我而言,它有所帮助。 您应该知道,在类似情况下,只需查看new
关键字即可。 例如,当他们在渲染函数中使用new Date()
时,人们经常会遇到相同的无限循环错误
就我而言,我有多个不同的 graphUri,具体取决于我的应用程序的网络选择。 我的问题是我使用了示例代码 ApolloWrapper,
const ApolloWrapper: (uri: string) => ApolloClient<any> | Error = (
uri: string
) => {
try {
return new ApolloClient({
link: link.concat(createHttpLink({ uri: uri })),
cache: new InMemoryCache(),
});
} catch (err) {
console.error("Failed to connect to client");
return Error(err);
}
};
然后将其用作
const GraphProvider: ({ children }: GProps) => any = ({ children }: GProps) => {
const client = Client.ApolloWrapper(config?.graphUri ?? "");
return (
<ApolloProvider client={client as ApolloClient<any>}>
{children}
</ApolloProvider>
);
};
当然,这里的默认 uri 是 '' ,它解析为空。
使用此配置尝试实例化 httpLink 时,它显然是错误的。 对于无法解决的任何其他网络问题也是如此。 在向 useQuery 添加一些错误检查并找到循环之前,我没有注意到这个问题。
对我来说,修复就像记忆 graphUri 一样简单,因此它不会持续抛出错误导致重新渲染,抛出错误导致重新渲染等。按如下方式替换包装器,以便它仅在 uri 更改时创建客户端的新实例。 我不确定我是否错过了 Apollo 文档中的一个超级简单的解决方案,但他们的东西似乎都不起作用。
const ApolloWrapper: (uri: string) => ApolloClient<any> | Error = (
uri: string
) => {
const client = useMemo(() => {
try {
return new ApolloClient({
link: link.concat(createHttpLink({ uri: uri })),
cache: new InMemoryCache(),
});
} catch (err) {
console.error("Failed to connect to client");
return Error(err);
}
}, [uri]);
return client;
};
我注意到客户端没有正确定义。 您能否尝试按如下方式初始化anotherClient
:
const anotherClient = new ApolloClient({
link: new HttpLink({
uri: 'https://my-url/online-service/graphql'
})
});
不要忘记在HttpLink
旁边导入ApolloClient
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.