Skip to content
Advertisement

How to get and set a ref for a newly cached related object in Apollo client InMemoryCache?

I have a set of related items like so:

book {
  id
  ...
  related_entity {
    id
    ...
  }
}

which apollo caches as two separate cache objects, where the related_entity field on book is a ref to an EntityNode object. This is fine, the related entity data is also used elsewhere outside of the context of a book so having it separate works, and everything seems well and good and updates as expected…except in the case where the related entity does not exist on the initial fetch (and thus the ref on the book object is null) and I create one later on.

I’ve tried adding an update function to the useMutation hook that creates the aforementioned related_entity per their documentation: https://www.apollographql.com/docs/react/caching/cache-interaction/#example-adding-an-item-to-a-list like this:

const [mutateEntity, _i] = useMutation(CREATE_OR_UPDATE_ENTITY,{
    update(cache, {data}) {
        cache.modify({
          id: `BookNode:${bookId}`,
          fields: {
            relatedEntity(_i) {
              const newEntityRef = cache.writeFragment({
                fragment: gql`
                  fragment NewEntity on EntityNode {
                    id
                    ...someOtherAttr
                  }`,
                data: data.entityData
              });
              return newEntityRef;
            }
          }
        })
    }
  });

but no matter what I seem to try, newEntityRef is always undefined, even though the new EntityNode is definitely in the cache and can be read just fine using the exact same fragment. I could give up and just force a refetch of the Book object, but the data is already right there.

Am I doing something wrong/is there a better way? Barring that is there another way to get a ref for a cached object given you have its identifier?

Advertisement

Answer

It looks like this is actually an issue with apollo-cache-persist – I removed it and the code above functions as expected per the docs. It also looks like I could instead update to the new version under a different package name apollo3-cache-persist, but I ended up not needing cache persistence anyway.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement