0
0
GraphQLquery~5 mins

Why mutations modify data in GraphQL

Choose your learning style9 modes available
Introduction

Mutations change data because they tell the system to add, update, or remove information. This helps keep data current and accurate.

When you want to add a new user to a website.
When you need to update a product's price in a store.
When you want to delete an old comment from a post.
When you want to change your profile information.
When you want to save a new order in an online shop.
Syntax
GraphQL
mutation {
  mutationName(input: {field1: value1, field2: value2}) {
    returnedField
  }
}
Mutations always start with the keyword mutation.
You provide input data inside parentheses to tell what to change.
Examples
This adds a new user named Alice who is 30 years old and returns her id and name.
GraphQL
mutation {
  addUser(input: {name: "Alice", age: 30}) {
    id
    name
  }
}
This updates the price of the product with id 123 to 19.99 and returns the id and new price.
GraphQL
mutation {
  updateProduct(input: {id: "123", price: 19.99}) {
    id
    price
  }
}
This deletes the comment with id 456 and returns if it was successful and a message.
GraphQL
mutation {
  deleteComment(input: {id: "456"}) {
    success
    message
  }
}
Sample Program

This mutation creates a new post with a title and content, then returns the post's id, title, and content.

GraphQL
mutation {
  createPost(input: {title: "Hello World", content: "My first post"}) {
    id
    title
    content
  }
}
OutputSuccess
Important Notes

Mutations are different from queries because they change data, while queries only read data.

Always check the response to confirm your data changed as expected.

Summary

Mutations let you add, update, or delete data.

They use the mutation keyword and take input to know what to change.

Use mutations whenever you want to modify stored information.