I use Apollo-Client to fetch data with GraphQL.
I want Apollo-Client to fetch the data from the cache and fetch it via network (in the background), too, so that the cache can be updated in case the data has changed. But I want Apollo-Client to return the cached data only (although it also fetches the data via network) so that my application can quickly continue running (using the cached data). (How) Can I achieve this?
Maybe I can use the cache-and-network fetch-policy?
const client = new ApolloClient({
uri: 'https://example.com/graphql',
cache: new InMemoryCache(),
defaultOptions: {
query: {
fetchPolicy: 'cache-and-network',
},
},
});
With that policy, it's not possible to use client.query(), so I needed to switch to client.watchQuery(). This method returns an observable from the zen-observable package. As usual with observables, you can subscribe to the changes of the observable. I wrote a function which, given a client, runs watchQuery and returns a promise containing the first result:
export function firstWatchedQuery(aClient, options) {
return new Promise((resolve, reject) => aClient.watchQuery(options).subscribe({
next: (value) => resolve(value),
error: (error) => reject(error),
}))
}
I can now use this function e.g. inside getServerSideProps() within a Next.js application:
export async function getServerSideProps() {
const { data } = await firstWatchedQuery(client, { query });
return { props: { objects: data.type.nodes }};
}
But the code does not work as I expect: It seems that it does not update the cache when reloading the page. What am I doing wrong?