您好,所以我在ReactJS应用程序上使用apollo-client已有一段时间了。我刚刚注意到,有时当我使用useQuery
钩子时,执行过程会完全忽略skip
参数,而只是继续onCompleted
(尽管没有任何数据)。有趣的是,它也没有向我的端点发出API请求。但是,如果我只是将skip
设置为false,则一切正常(按预期)。
而且,并非每次我将useQuery
与skip
一起使用时,似乎都可以使用某些方法,而不能使用其他方法。
为什么阿波罗忽略了skip
参数,而只用空数据立即执行onCompleted
?除了useLazyQuery
以外有其他解决方法吗?
const userQuery = useQuery(GET_USER, {
variables: {
value: userId,
},
skip: true,
onCompleted: props => {
console.log(`props => `, props)
const {
user: { type, role, firstName, lastName, permissions },
} = props;
setValue('firstName', firstName);
setValue('lastName', lastName);
setValue(
'type',
userTypes.find(({ value }) => value === type),
);
setValue(
'role',
userRoles.find(({ value }) => value === role),
);
},
});
其他说明:
•从onCompleted函数记录道具的输出为props => undefined
。
•我添加了skip: true
只是为了证明它实际上不起作用。
•如果我自己记录userQuery
,那么在第一个日志中,userQuery.called
等于true(但正如我之前所说,实际上没有执行过API调用)
"@apollo/react-hooks": "^3.1.5",
"apollo-cache-inmemory": "^1.6.3",
"apollo-client": "^2.6.10",
"apollo-datasource-rest": "^0.6.6",
"apollo-link": "^1.2.13",
"apollo-link-context": "^1.0.19",
"apollo-link-error": "^1.1.12",
"apollo-link-rest": "^0.7.3",
"apollo-link-retry": "^2.2.15",
"apollo-link-token-refresh": "^0.2.7",
"apollo-upload-client": "^11.0.0",
"react": "16.10.2",
"react-apollo": "^3.1.3",
useLazyQuery
似乎工作正常,因此,为此,您可以将其与useEffect
结合使用以解决此问题。
答案 0 :(得分:-1)
阿波罗客户端有问题。 skip 中的错误是一个令人讨厌的错误。你可以放弃 GraphQL,或者绕过它们。我建议放弃它,但如果你不能,这里有一个解决方法。该模块的工作方式与 useQuery 类似,并且可以跳过工作。它不完整的完整规范,但应该让你开始。
import { useEffect, useState } from 'react';
import { QueryHookOptions, useApolloClient } from '@apollo/react-hooks';
import { ApolloQueryResult, NetworkStatus, QueryOptions, ApolloError } from 'apollo-client';
interface DocumentNode {
loc: {
source: {
body: string;
};
};
}
interface QueryResult<T> extends ApolloQueryResult<T> {
error?: Error | ApolloError;
refetch?: () => void;
}
/**
* Method: useQuery
* Description: enable skip on useQuery. There is a bug that currently ignores it. The bug is confirmed in the 3.2 release as well.
* Note: https://github.com/apollographql/react-apollo/issues/3492
*/
export function useQuery<T>(
query: DocumentNode,
options?: QueryHookOptions
): QueryResult<T | null> {
// Note: using useApolloClient because useLazyQuery fires on initialization. If we are skipping, we don't even want the first fire.
const apolloClient = useApolloClient();
const [result, setQueryResult] = useState<QueryResult<T | null>>({
// Note: initial state
data: null,
loading: false,
stale: false,
networkStatus: NetworkStatus.ready
});
const setResult = (res: QueryResult<T | null>) => {
// Note: GraphQL and Apollo can't decide if they want to return errors, or error in the type contract. I want to be sure the contract is stable. If there are errors, there will be error.
if (res.errors?.length && !res.error) {
[res.error] = res.errors;
}
// Note: Functions should always exist even if the query is not complete.
if (!res.refetch) {
res.refetch = () => {
if (!result.loading) {
execQuery();
}
};
}
setQueryResult(res);
};
const execQuery = async () => {
// Note: loading state. Not spreading "...result" to allow errors to be reset.
setResult({
data: options?.fetchPolicy === 'no-cache' ? null : result.data,
loading: true,
networkStatus: NetworkStatus.loading,
stale: true
});
try {
const queryOptions = ({
...options,
query
} as unknown) as QueryOptions;
await apolloClient
.query(queryOptions)
.then(result => {
setResult(result);
if(options?.onCompleted) options.onCompleted(result.data);
})
.catch(err => {
setResult(err);
if(options?.onError) options.onError(err);
});
} catch (err) {
// Note: fail state
setResult({
...result,
loading: false,
errors: [err],
error: err,
stale: true,
networkStatus: NetworkStatus.error
});
}
};
useEffect(() => {
// Note: Skip Functionality
if (!result.loading && options?.skip !== true) {
execQuery();
}
// Note only listen too explicit variables. If you listen to whole objects they are always different and will cause endless loops.
}, [options?.skip, query.loc.source.body]);
return result;
}