Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apollo writeFragment not updating data

In react-apollo 2.0.1 I have a graphql type that looks like this:

type PagedThing {
  data: [Thing]
  total: Int
}

When doing the following writeFragment

  client.writeFragment({
    id,
    fragment: gql`
      fragment my_thing on Thing {
        status
      }
    `,
    data: {
      status
    }
  })

The cache is not update and the new data is not shown on the UI. Is there something else that need to be done?

PS: To be safe I used fragment matching

Edit 1:

I receive an error of:

Cannot match fragment because __typename property is missing: {"status":"online"}

So I changed the code to:

client.writeFragment({
    id,
    fragment: gql`
      fragment my_thing on Thing {
        status
      }
    `,
    data: {
      __typename: 'Thing',
      status
    }
  })

And no error is thrown but the updated still do not happen

like image 722
FabioCosta Avatar asked Feb 05 '18 21:02

FabioCosta


People also ask

How do you update cache after mutation Apollo?

If a mutation updates a single existing entity, Apollo Client can automatically update that entity's value in its cache when the mutation returns. To do so, the mutation must return the id of the modified entity, along with the values of the fields that were modified.

How do I reset my Apollo cache?

Resetting the cache Sometimes, you might want to reset the cache entirely, such as when a user logs out. To accomplish this, call client. resetStore . This method is asynchronous, because it also refetches any of your active queries.

What is in memory cache in Apollo?

Overview. Apollo Client stores the results of your GraphQL queries in a local, normalized, in-memory cache. This enables Apollo Client to respond almost immediately to queries for already-cached data, without even sending a network request. The Apollo Client cache is highly configurable.


2 Answers

Turns out I needed to not only add the __typename as the ID needed to be the one resolved by default (Explained here)

So I needed to do the following in order to make it work:

client.writeFragment({
  id: `Thing:${id}`,
  fragment: gql`
    fragment my_thing on Thing {
      status
    }
  `,
  data: {
    __typename: 'Thing',
    status
  }
})
like image 175
FabioCosta Avatar answered Sep 27 '22 20:09

FabioCosta


it appears that the framework has been extended to provide a method called 'identify' to avoid this problem (in case they change implementation later)

cache.modify({
  id: cache.identify(myPost),
             ^
  fields(fieldValue, details) {
    return details.INVALIDATE;
  },
});

https://www.apollographql.com/docs/react/caching/cache-interaction/#example-invalidating-fields-within-a-cached-object

like image 42
eAndy Avatar answered Sep 27 '22 19:09

eAndy