Mutation and update cache

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

githubsrc/app/Todo/TodoItem.ts
import { GET_MY_TODOS } from './TodoPrivateList'
const TOGGLE_TODO = gql`
mutation toggleTodo ($id: Int!, $isCompleted: Boolean!) {
update_todos(where: {id: {_eq: $id}}, _set: {is_completed: $isCompleted}) {
affected_rows
}
}
`
+ const REMOVE_TODO = gql`
+ mutation removeTodo ($id: Int!) {
+ delete_todos(where: {id: {_eq: $id}}) {
+ affected_rows
+ }
+ }
+ `;

We have a function defined to handle the button click to remove a todo. Let's update the function to add apollo.mutate code.

removeTodo(e) {
e.preventDefault();
e.stopPropagation();
+ this.apollo.mutate({
+ mutation: REMOVE_TODO,
+ variables: { id: this.todo.id },
+ optimisticResponse: {},
+ update: (cache) => {
+ const existingTodos: any = cache.readQuery({ query: GET_MY_TODOS });
+ const newTodos = existingTodos.todos.filter(t => (t.id !== this.todo.id));
+ cache.writeQuery({
+ query: GET_MY_TODOS,
+ data: { todos: newTodos }
+ });
+ },
+ }).subscribe(({ data }) => {
+ console.log('got data', data);
+ },(error) => {
+ console.log('there was an error sending the query', error);
+ });
}
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
© 2024 Hasura Inc. All rights reserved
Github
Titter
Discord
Facebook
Instagram
Youtube
Linkedin
graphql-handbook