我正在像这样设置阿波罗客户端。
const defaultOptions = {
watchQuery: {
fetchPolicy: 'cache-and-network',
errorPolicy: 'ignore',
},
query: {
fetchPolicy: 'cache-and-network',
errorPolicy: 'all',
},
mutate: {
errorPolicy: 'all',
},
};
return new ApolloClient({
link: ApolloLink.from([authLink, errorLink, webSocketOrHttpLink]),
defaultOptions, // Typescript don't like this.
queryDeduplication: true,
});
打字稿给出此错误:
Type '{ watchQuery: { fetchPolicy: string; errorPolicy: string; }; query: { fetchPolicy: string; errorPolicy: string; }; mutate: { errorPolicy: string; }; }' is not assignable to type 'DefaultOptions'.ts(2322)
ApolloClient.d.ts(23, 5): The expected type comes from property 'defaultOptions' which is declared here on type 'ApolloClientOptions<NormalizedCacheObject>'
根据文档,这就是应该完成的方式。
如何使用正确的类型构建defaultOptions
?
如果你检查库的代码,那么,这里似乎有问题
//defination of default options
export interface DefaultOptions {
watchQuery?: Partial<WatchQueryOptions>;
query?: Partial<QueryOptions>;
mutate?: Partial<MutationOptions>;
}
//defination of QueryOptions
export interface QueryOptions<TVariables = OperationVariables>
extends QueryBaseOptions<TVariables> {
/**
* Specifies the {@link FetchPolicy} to be used for this query
*/
fetchPolicy?: FetchPolicy;
}
//valid value for FetchPolicy type
export type FetchPolicy =
| 'cache-first'
| 'network-only'
| 'cache-only'
| 'no-cache'
| 'standby';
export type WatchQueryFetchPolicy = FetchPolicy | 'cache-and-network';
因此,对于查询选项,您应该为FetchPolicy
传递任何有效值,'cache-and-network'
不是有效值。
在此处查看文档: https://github.com/apollographql/apollo-client/blob/main/src/core/watchQueryOptions.ts
2021
:如果您尝试将cache-and-network
用作query.fetchPolicy
的默认值:
为什么cache-and-network
不允许故意用于query
的原因早在 2019 年就在这里解释: https://github.com/apollographql/apollo-client/issues/3130#issuecomment-478409066
基本上,query()
的行为/逻辑不支持这种策略。因此,他们在打字级别阻止它。
React useQuery() hook
如果你使用的是 react,useQuery()
钩子遵循watchQuery
的行为而不是query
。因此,配置watchQuery
就足够了:
import {
ApolloClient,
InMemoryCache,
HttpLink,
DefaultOptions
} from "@apollo/client";
const defaultOptions: DefaultOptions = {
watchQuery: {
fetchPolicy: "cache-and-network",
errorPolicy: "ignore",
notifyOnNetworkStatusChange: true
}
};
export const platformClient = new ApolloClient({
link: new HttpLink({
uri: "https://xxxxx",
credentials: "same-origin"
}),
cache: new InMemoryCache(),
defaultOptions
});