This course is no longer maintained and may be out-of-date. While it remains available for reference, its content may not reflect the latest updates, best practices, or supported features.

Mutation and update cache

Now let's do the integration part. Open components/Todo/TodoItem.js and add the following code to define the delete mutation

githubcomponents/Todo/TodoItem.js
const TodoItem = ({index, todo, client}) => {
+ const REMOVE_TODO = gql`
+ mutation removeTodo ($id: Int!) {
+ delete_todos(where: {id: {_eq: $id}}) {
+ affected_rows
+ }
+ }
+ `;
+ const [removeTodoMutation] = useMutation(REMOVE_TODO);

We have a function defined to handle the button click to remove a todo. Let's update the function to use removeTodoMutation mutate function.

const removeTodo = (e) => {
e.preventDefault();
e.stopPropagation();
+ removeTodoMutation({
+ variables: {id: todo.id},
+ optimisticResponse: true,
+ update: (cache) => {
+ const existingTodos = cache.readQuery({ query: GET_MY_TODOS });
+ const newTodos = existingTodos.todos.filter(t => (t.id !== todo.id));
+ cache.writeQuery({
+ query: GET_MY_TODOS,
+ data: {todos: newTodos}
+ });
+ }
+ });
};
Did you find this page helpful?
Start with GraphQL on Hasura for Free
  • ArrowBuild apps and APIs 10x faster
  • ArrowBuilt-in authorization and caching
  • Arrow8x more performant than hand-rolled APIs
Promo
footer illustration
Brand logo
© 2025 Hasura Inc. All rights reserved
Github
Titter
Discord
Facebook
Instagram
Youtube
Linkedin
graphql-handbook