We use update mutations to change existing data in a database through GraphQL. It helps keep information current without deleting and recreating records.
0
0
Update mutation pattern in GraphQL
Introduction
When you want to change a user's email address in your app.
When you need to update the status of an order from 'pending' to 'shipped'.
When correcting a typo in a product description.
When changing a user's password securely.
When updating a blog post's content or title.
Syntax
GraphQL
mutation UpdateEntityName($id: ID!, $input: UpdateEntityInput!) {
updateEntityName(id: $id, input: $input) {
id
field1
field2
...
}
}The mutation name usually starts with update followed by the entity name.
You pass the id of the item to update and an input object with new values.
Examples
This updates a user's name and email by their ID.
GraphQL
mutation UpdateUser($id: ID!, $input: UpdateUserInput!) {
updateUser(id: $id, input: $input) {
id
name
email
}
}This updates a blog post's title and content.
GraphQL
mutation UpdatePost($id: ID!, $input: UpdatePostInput!) {
updatePost(id: $id, input: $input) {
id
title
content
}
}Sample Program
This mutation updates the email of the user with ID 123 to 'newemail@example.com'. It returns the user's id, name, and updated email.
GraphQL
mutation UpdateUserEmail($id: ID!, $input: UpdateUserInput!) {
updateUser(id: $id, input: $input) {
id
name
email
}
}
# Variables:
# {
# "id": "123",
# "input": {"email": "newemail@example.com"}
# }OutputSuccess
Important Notes
Always provide the id to specify which record to update.
The input object should only include fields you want to change.
Check your GraphQL schema for exact input types and required fields.
Summary
Update mutations change existing data by specifying an ID and new values.
They help keep data accurate without deleting or recreating records.
Use clear input objects to send only the fields you want to update.