Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

342
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda