Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

333
Views
Get first result of WatchQuery Method of Apollo-Client (when called with cache-and-network fetch-policy)

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?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!