Guillermo Grau
Guillermo Grau

Reputation: 258

Optimistic update for a deletion mutation

I'm writing a deletion mutation. The mutation should delete a Key node and update the viewer's keys collection (I'm using Relay-style collections: viewer { keys(first: 3) { edges { node { ... }}}}.

Following the advice here, I'm using the FIELDS_CHANGE config for simplicity, and it's actually working:

export class DeleteKeyMutation extends Relay.Mutation {
  static fragments = {
    viewer: () => Relay.QL`
      fragment on Viewer { id }
    `,
  };
  getMutation() { return Relay.QL`mutation {deleteKey}`; }
  getVariables() {
    return {
      id: this.props.id,
    };
  }
  getFatQuery() {
    return Relay.QL`
      fragment on DeleteKeyPayload {
        viewer { keys }
      }
    `;
  }
  getConfigs() {
    return [
      {
        type: 'FIELDS_CHANGE',
        fieldIDs: {
          viewer: this.props.viewer.id,
        },
      },
    ];
  }
}

Now, how should I write an optimistic mutation for this? I've tried different approaches but none worked.

Upvotes: 4

Views: 1240

Answers (1)

freiksenet
freiksenet

Reputation: 3679

Optimistic update in Relay is just a simulation of what the server will return if operation succeeds. In your case you are removing one key, meaning the result would be an object without that key.

getOptimisticUpdate() {
  return {
    viewer: {
      id: this.props.viewer.id,
      keys: {
        edges: this.props.viewer.keys.edges.filter((keyEdge) => key.node.id !== this.props.id)
      }
    }
  };
}

You will also need to include the keys to your fragments so they are available in the mutation.

static fragments = {
  viewer: () => Relay.QL`
    fragment on Viewer { id, keys { edges(first: 3) { node { id } }}
  `,
};

The problem with this approach is that it relies on your mutation to know what's your current keys pagination. If you are operating on the whole Connection at once, it is fine, but if you are using Relay pagination you should consider using other mutation operations.

There is NODE_DELETE, which can delete all occurrences of your key from Relay store or you can use RANGE_DELETE to only delete it from your current connection.

Upvotes: 3

Related Questions