1
votes

Is it possible to reuse a mutation?

Let's say there exists a mutation UpdateItemMutation which I'm passing props to, but sometimes I just want to update a specific attribute.

i.e. I want to be able to do:

UpdateItemMutation({prop1: 'Data', prop2: 'Data2'})
UpdateItemMutation({prop1: 'Data'})
UpdateItemMutation({prop2: 'Data2'})

Unfortunately, my optimistic config complains since I'm passing an undefined to it.

Also, since I have to take into account for the mutation updating everything, this would re-query the whole thing, ideally updating 'prop1' would only do a fatQuery for 'prop1'.

Using @include if the prop is defined doesn't seem to work here.

1
Can you post your mutation code and also the error you're getting?Chris

1 Answers

1
votes

Currently no direct way is available, though there is a workaround, that too if you don't mind fetching the whole item in response to the mutation.

As you want to update variable number of attributes of an item, you may write a mutation (server-side) that takes a list of attributes and a list of values.

// Using `graphql-relay` library's helper function `mutationWithClientMutationId`.
const UpdateItemMutation = mutationWithClientMutationId({
  name: 'UpdateItem',
  inputFields: {
    itemId: { type: new GraphQLNonNull(GraphQLID) }
    properties: { type: new GraphQLList(GraphQLString) },
    values: { type: new GraphQLList(GraphQLString) },
  },
  outputFields: {
    item: {
      type: ItemType,
      resolve: (item) => item,
    },
  },
  mutateAndGetPayload: ({itemId, properties, values, ...args}) => {
    // Iterate over the properties and values.
    // Update the item with itemId.

    return item;
  },
});

The client-side mutation is invoked like below:

Relay.Store.commitUpdate(new UpdateItemMutation({
  item: this.props.item,
  properties: ['prop1', 'prop2'],
  values: ['value1', 'value2'],
}));

Regarding optimistic update in the client-side mutation, you can craft the return value from properties and values i.e., the updated attributes and their values.

To the best of my knowledge, including fields conditionally in the fat query is not supported by Relay at the moment. Unlike Relay container, we cannot use variables in the fat query. Seeing the current efforts by Relay contributors, I believe, the mutation APIs will be a lot more powerful yet streamlined in the near future.