0
0
GraphqlHow-ToBeginner · 3 min read

How to Return Data from Mutation in GraphQL

In GraphQL, you return data from a mutation by specifying the fields you want in the mutation's selection set, just like a query. Use mutation with the desired return fields after the mutation call to get the updated or created data.
📐

Syntax

A GraphQL mutation returns data by including a selection set of fields after the mutation call. The syntax looks like this:

  • mutation: keyword to start a mutation operation.
  • mutationName: the mutation you want to perform.
  • input: the input arguments for the mutation.
  • { ...fields }: the fields you want returned from the mutation result.
graphql
mutation MutationName($input: InputType!) {
  mutationName(input: $input) {
    field1
    field2
    nestedField {
      subField
    }
  }
}
💻

Example

This example shows a mutation to add a new user and return the user's id and name after creation.

graphql
mutation AddUser($input: AddUserInput!) {
  addUser(input: $input) {
    id
    name
  }
}

# Variables:
# {
#   "input": {"name": "Alice"}
# }
Output
{ "data": { "addUser": { "id": "123", "name": "Alice" } } }
⚠️

Common Pitfalls

Common mistakes when returning data from mutations include:

  • Not specifying any fields after the mutation call, which returns no data.
  • Expecting the mutation to return all fields automatically without listing them.
  • Confusing mutation input arguments with the return fields.

Always explicitly list the fields you want to receive in the mutation response.

graphql
mutation WrongAddUser {
  addUser(input: {name: "Bob"})
}

# This returns no data because no fields are requested.

mutation CorrectAddUser {
  addUser(input: {name: "Bob"}) {
    id
    name
  }
}
Output
{ "data": { "addUser": null } } # vs { "data": { "addUser": { "id": "124", "name": "Bob" } } }
📊

Quick Reference

Tips for returning data from mutations:

  • Always include a selection set with the fields you want returned.
  • Use the same syntax as queries to specify return fields.
  • Return only the data needed to update your UI or state.

Key Takeaways

Specify the fields you want returned in the mutation's selection set.
Mutations return data like queries, so always list return fields explicitly.
Not requesting fields returns no data from the mutation.
Use returned data to update your app state or UI after mutation.
Mutation input arguments and return fields are separate parts of the syntax.