0
votes

I am using react-apollo to manage client store in my react application so there is no backend graphql server. Everything related to apollo is running in the client side. I store all UI state in the cache of ApolloClient. And I also define all resolvers in the client side.

Below is the code to new a client instance:

new ApolloClient({
    cache,
    resolvers: {
      Mutation: {
        ...cartResolvers,
      },
    },
    typeDefs: [typeDefs]
  });

I have read this article https://www.apollographql.com/docs/angular/features/cache-updates/#automatic-store-updates about automatically update store by using ID in apollo graphql mutation and query. But it doesn't seem to work. I have below query and mutation:

export const queryCart = gql`
  {
    cart @client {
      items {
        id
        name
        price
        quantity
        image
      }
    }
  }
`;

export const addToBasket = gql`
  mutation addToBasket($sku: ID!) {
    addToBasket(id: $sku)  @client {
      items {
        id
        name
        price
        quantity
        image
      }
    }
  }
`;

And I have defined the resolver for that mutation addToBasket.

const addToBasket = (_parent: any, item: { id: string }, { cache }: ResolverCacheType): CartProps => {
   ...
   return {
      items: [ {id, name, price, quantity, image } ]
   }
}

I found that even I return the id in the resolver, the cache is not updated and the query is not reactive. I can make it work by manually update the cache data in the resolve by cache.writeData.

1

1 Answers

0
votes

Your use case is different from the automatic update scenario provided by react-apollo: The mutation you run does not update the item itself. Instead, it updates an array that is not keyed in any way for react-apollo to track its changes.

To take advantage of the auto update feature, you can change the data structure of the item array from the simple array it is now to an object that looks similar to this:

{ _id, [{id, name, price, ...}]}

Both the query and the mutation should return this object. Then you have the same setup as the example in the doc. After the mutation runs, the return object has the same _id as the local cache, therefore react-apollo knows it needs to update the cache data.

Alternatively, you can either manually use cache.writeData as you already mentioned or use refetchQueries to update the cart items array.