Mutation and update cache

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

githubsrc/components/TodoItem.vue
<script>
import gql from 'graphql-tag';
import { GET_MY_TODOS } from "./TodoPrivateList.vue";
const TOGGLE_TODO = gql`
mutation update_todos($id: Int!, $isCompleted: Boolean!) {
update_todos(where: { id: { _eq: $id } }, _set: { is_completed: $isCompleted }) {
affected_rows
}
}
`;
+ const REMOVE_TODO = gql`
+ mutation delete_todos($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 this.$apollo.mutate code.

methods: {
handleTodoToggle: function (todo) {
...
},
handleTodoDelete: function(todo) {
// delete todo from db
+ this.$apollo.mutate({
+ mutation: REMOVE_TODO,
+ variables: {
+ id: todo.id,
+ },
+ update: (store, { data: { delete_todos } }) => {
+ if (delete_todos.affected_rows) {
+ if (this.type === "private") {
+ const data = store.readQuery({
+ query: GET_MY_TODOS
+ });
+ data.todos = data.todos.filter(t => {
+ return t.id !== todo.id;
+ });
+ store.writeQuery({
+ query: GET_MY_TODOS,
+ data
+ });
+ }
+ }
+ },
+ });
}
}

Again, we are making a simple mutation to delete a todo and update the cache. This pattern should be familiar enough by now.