Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a GraphQL/Relay mutation that creates a model, is there a way to get back the model ID?

Tags:

relayjs

We're using Relay and GraphQL in a new project.

We've got a Relay mutation that creates a new model in the DB:

export default class AddCampaignMutation extends Relay.Mutation {
    getMutation() {
        return Relay.QL`mutation { addCampaign }`;
    }
    getVariables() {
        return {
            type: this.props.campaignType
        };
    }
    getFatQuery() {
        return Relay.QL`
            fragment on AddCampaignPayload {
                campaignEdge
                viewer
            }
        `;
    }
    getConfigs() {
        return [{
            type: 'RANGE_ADD',
            parentName: 'viewer',
            parentID: this.props.viewer.id,
            connectionName: 'campaigns',
            edgeName: 'campaignEdge',
            rangeBehaviors: {
              '': 'append',
            },
        }];
    }
    static fragments = {
        viewer: () => Relay.QL`
            fragment on User {
                id
            }
        `,
    };
}

However, since none of the components are currently querying for the range specified in RANGE_ADD (viewer { campaigns }), Relay intelligently excludes that query from the AddCampaignPayload.

This results in a console warning:

Warning: writeRelayUpdatePayload(): Expected response payload to include the newly created edge `campaignEdge` and its `node` field. Did you forget to update the `RANGE_ADD` mutation config?

I really want to get back the ID of the newly created model, so that I can navigate the client to it. For example, getting back the new campaignEdge, I want to send the client to /campaigns/${campaignEdge.node.id}.

Is there any way to tell Relay to fetch that edge? Have I configured this mutation correctly?

like image 377
colllin Avatar asked Oct 30 '15 21:10

colllin


1 Answers

You can use REQUIRED_CHILDREN in this context. For more details, see https://github.com/facebook/relay/issues/237 and https://github.com/facebook/relay/issues/236.

REQUIRED_CHILDREN lets you specify an extra data dependency for exactly this pattern.

like image 198
taion Avatar answered Oct 19 '22 23:10

taion