Mutation and update cache

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

githubsrc/components/Todo/TodoItem.js
const TodoItem = ({index, todo, client}) => {
+ 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 client.mutate code.

const removeTodo = (e) => {
e.preventDefault();
e.stopPropagation();
+ client.mutate({
+ mutation: REMOVE_TODO,
+ variables: {id: todo.id},
+ optimisticResponse: {},
+ 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}
+ });
+ }
+ });
};