Reputation: 26662
I'm setting up Apollo Client like this.
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,
});
Typescript gives this error:
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>'
Per the docs, this is how it's supposed to be done.
How can I structure defaultOptions
with proper types?
Upvotes: 3
Views: 6849
Reputation: 4465
2021:
If you are trying to use cache-and-network
as default for query.fetchPolicy
:
The reason why cache-and-network
is not allowed intentionally for query
is explained back in 2019 here:
https://github.com/apollographql/apollo-client/issues/3130#issuecomment-478409066
Basically, the behaviour/logic of query()
is not supporting this strategy. So, they block it at typing level.
React useQuery() hook
And if you're using react, the useQuery()
hook is following behaviour of watchQuery
instead of query
. So configuring the watchQuery
is enough:
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
});
Upvotes: 3
Reputation: 176896
if you check code of library then , it seems here is issue
//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';
so here for query options you should pass any valid value for FetchPolicy
and 'cache-and-network'
is not valid value.
check documentation here : https://github.com/apollographql/apollo-client/blob/main/src/core/watchQueryOptions.ts
Upvotes: 7