0
0
GraphqlHow-ToBeginner · 3 min read

How to Delete Data Using Mutation in GraphQL

In GraphQL, you delete data by defining a mutation that calls a delete resolver on the server. The mutation usually takes an identifier (like an ID) as an argument and returns confirmation or the deleted item. You run this mutation like a query but it changes data on the server.
📐

Syntax

A GraphQL delete mutation typically looks like this:

  • mutation: Keyword to start a mutation operation.
  • deleteItem: The name of the mutation field that deletes data.
  • id: The argument specifying which item to delete.
  • return fields: The data you want back after deletion, often the deleted item's ID or status.
graphql
mutation DeleteItem($id: ID!) {
  deleteItem(id: $id) {
    id
    success
    message
  }
}
💻

Example

This example shows a mutation to delete a user by their ID and get back a success message.

graphql
mutation DeleteUser($id: ID!) {
  deleteUser(id: $id) {
    id
    success
    message
  }
}

# Variables:
# {
#   "id": "123"
# }
Output
{ "data": { "deleteUser": { "id": "123", "success": true, "message": "User deleted successfully" } } }
⚠️

Common Pitfalls

Common mistakes when deleting data with mutations include:

  • Not providing the required id argument, causing errors.
  • Expecting the mutation to return deleted data without specifying return fields.
  • Confusing queries with mutations; mutations must be explicitly declared.
  • Not handling errors or success responses properly in the client.
graphql
Wrong:
mutation {
  deleteUser {
    id
  }
}

Right:
mutation DeleteUser($id: ID!) {
  deleteUser(id: $id) {
    id
    success
    message
  }
}
📊

Quick Reference

PartDescription
mutationStarts the mutation operation
deleteItemName of the delete mutation field
idUnique identifier of the item to delete
return fieldsData returned after deletion (e.g., id, success, message)

Key Takeaways

Use a GraphQL mutation with an ID argument to delete data.
Always specify what data you want returned after deletion.
Mutations must be explicitly declared with the mutation keyword.
Handle success and error responses in your client code.
Check that required arguments like ID are provided to avoid errors.