Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

337
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda