0
0
GraphqlHow-ToBeginner · 3 min read

How to Update Data Using Mutation in GraphQL

To update data in GraphQL, use a mutation operation with an update field that accepts input parameters specifying the changes. The mutation returns the updated data so you can confirm the update.
📐

Syntax

A GraphQL mutation to update data typically has this structure:

  • mutation: The keyword to start a mutation operation.
  • updateEntity: The mutation field name that performs the update (name depends on your schema).
  • input: An argument object containing the data to update, usually including an id to identify the record and fields to change.
  • { ... }: The selection set specifying which fields to return after the update.
graphql
mutation UpdateEntity($input: UpdateEntityInput!) {
  updateEntity(input: $input) {
    id
    name
    description
  }
}
💻

Example

This example updates a user's name and email by their ID and returns the updated fields.

graphql
mutation UpdateUser($input: UpdateUserInput!) {
  updateUser(input: $input) {
    id
    name
    email
  }
}

# Variables:
# {
#   "input": {
#     "id": "123",
#     "name": "Alice Smith",
#     "email": "alice.smith@example.com"
#   }
# }
Output
{ "data": { "updateUser": { "id": "123", "name": "Alice Smith", "email": "alice.smith@example.com" } } }
⚠️

Common Pitfalls

Common mistakes when updating data with mutations include:

  • Not providing the required id or unique identifier to specify which record to update.
  • Omitting required fields in the input object, causing validation errors.
  • Expecting the mutation to return updated data but not specifying the fields to return in the selection set.
  • Confusing queries with mutations; updates must use mutation keyword.
graphql
/* Wrong: Missing id to identify record */
mutation {
  updateUser(input: {name: "Bob"}) {
    id
    name
  }
}

/* Right: Include id to specify which user to update */
mutation {
  updateUser(input: {id: "123", name: "Bob"}) {
    id
    name
  }
}
📊

Quick Reference

ConceptDescription
mutationKeyword to perform data changes
updateFieldMutation field that updates data (name varies)
inputArgument object with update details, including id
selection setFields to return after update to confirm changes

Key Takeaways

Use the mutation keyword with an update field to change data in GraphQL.
Always provide the unique identifier (like id) in the input to specify which record to update.
Specify the fields you want returned after the update to verify changes.
Mutations must be distinct from queries and use the mutation operation.
Check your schema for the exact mutation name and input structure.