Search code examples
reactjsrelayjsgraphql-js

Returning Promise from mutateAndGetPayload


I'm trying to return a Promise from the mutateAndGetPayload function of a mutationWithClientMutationId, but i can't seem to get a response back. The request is just left as pending until it times out.

Some sample code:

mutateAndGetPayload: ({clientMutationId, ...args}) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve("Resolved")
        }, 500)
    })
}, ...

Looking through the source code and the test schema it should be possible to return a Promise, so i must be doing something wrong. Any guidance here?

EDIT: Turns out the promise resolves just fine, there's some problem with another part of my code. Can't really get any good traces as to where that is though.


Solution

  • It's expected that the return value of mutateAndGetPayload is an object whose keys match the configured outputFields of the mutation. Also, the payload must contain clientMutationId so that the client side can correlate the response to the related client-side mutation transaction.

    import {mutationWithClientMutationId} from 'graphql-relay-js';
    const myMutation = mutationWithClientMutationId({
      /*...*/
      outputFields: {
        foo: {type: GraphQLString, resolve: (payload) => payload.fooString},
      },
      mutateAndGetPayload() {
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            const payload = {fooString: 'Resolved'};
            resolve(payload);
          }, 500);
        });
      },
    });
    

    The example above uses the mutationWithClientMutationId helper from graphql-relay-js to automatically add the clientMutationId to the outgoing payload, as well as the correct output and input types. See how it does it, here: https://github.com/graphql/graphql-relay-js/blob/master/src/mutation/mutation.js