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

146
Vistas
Custom merge function is not being called after updating field with cache.modify

I have written a custom merge function for the field products on type Session. It seems the merge function is only being called when I initialise the object Session:1 with its products, and not when I update products later using cache.modify.

My merge function:

const client = new ApolloClient({
  uri: 'http://localhost:8081/graphql',
  cache: new InMemoryCache({
    typePolicies: {
      Session: {
        fields: {
          products: {
            merge (existing, incoming) {
              // this is only being called on useQuery(HydrateSession), not useMutation(UpsertProduct)
              console.log('existing', JSON.stringify(existing, null, 2))
              console.log('incoming', JSON.stringify(incoming, null, 2))
              // remove duplicates when latestProduct has the same id as an existing product — [..., latestProduct]
              if (incoming.filter(p => p.id === incoming[incoming.length - 1].id).length > 1) return existing
              return incoming
            }
          }
        }
      }
    }
  })
})

Initialisation of Session:

const HydrateSession = gql`
  query {
    session {
      id
      products {
        id
      }
    }
  }
`

...

useQuery(HydrateSession)

Updating products later using cache.modify:

const UpsertProduct = gql`
  mutation UpsertProduct($product: ProductInput!) {
    upsertProduct(product: $product) {
      id
    }
  }
`

...

const [upsertProductMutation] = useMutation(UpsertProduct)

const onClick = async () => {
  await upsertProductMutation({
    variables: {
      product: {
        id: 2
      }
    },
    update: (cache, mutationResult) => {
      cache.modify({
        id: 'Session:1',
        fields: {
          products: previous => [...previous, mutationResult.data.upsertProduct]
        }
      })
    }
  })
}

I have a full working example here https://github.com/jsindos/apollo-play, run npm i and then start two separate processes with npm start and npm serve. After clicking the button triggering the mutation, the merge function is not run (as seen by the absence of console.log statements in the console).

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

modify circumvents any merge functions you've defined, which means that fields are always overwritten with exactly the values you specify.

  • https://www.apollographql.com/docs/react/caching/cache-interaction/#using-cachemodify

Reading documentation is a good thing.

about 4 years ago · Juan Pablo Isaza Denunciar
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