1
votes

I want to utilize apollo cache with apollo-client api directly using fetchPolicy 'cache-and-network'. Seems that we have to use watchQuery api instead of query but unfortunately I couldn't make it work.

So could you guys please give me some example code to use 'watchQuery' to get data as what we get from 'query': loading, data, networkStatus...?

client.query({ query: Query.getUserById, fetchPolicy: 'cache-and-network', variables: { userId } }).then(data => { console.log(data.loading, data.getUserById) })

2

2 Answers

3
votes

I think apollo already provide any configuration for all operation includes fetch-policy and it's documentation mostly cover all use case

Can you provide your code? i wonder why Query doesn't work when you using another type of cache

0
votes

2021:

If you're using react, the useQuery() hook is already following behaviour of watchQuery instead of query. So you are allowed to do this:

  const { loading, error, data, refetch } = useQuery(query, {
    fetchPolicy: "cache-and-network"
  });

Or set it as defaultOptions when creating the apollo client:

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
});

Some explanation on why cache-and-network is not allowed for query intentionally.

The reason 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 fetching strategy. So, they block it at typing level.