Mutation and update cache

Open components/Todo/TodoPrivateList.js and import useMutation React hook and add the bulk delete mutation.

githubcomponents/Todo/TodoPrivateList.js
import React, { Fragment, useState } from "react";
+ import { useQuery, useMutation } from "@apollo/react-hooks";
import gql from "graphql-tag";
import TodoItem from "./TodoItem";
import TodoFilters from "./TodoFilters";
const GET_MY_TODOS = gql`
query getMyTodos {
todos(
where: { is_public: { _eq: false } }
order_by: { created_at: desc }
) {
id
title
created_at
is_completed
}
}
`;
+ // Remove all the todos that are completed
+ const CLEAR_COMPLETED = gql`
+ mutation clearCompleted {
+ delete_todos(where: {is_completed: {_eq: true}, is_public: {_eq: false}}) {
+ affected_rows
+ }
+ }
+ `;

Use the useMutation React hook and update the clearCompleted function as below

const filterResults = filter => {
setState({
...state,
filter: filter
});
};
+ const [clearCompletedTodos] = useMutation(CLEAR_COMPLETED);
clearCompleted() {
+ clearCompletedTodos({
+ optimisticResponse: true,
+ update: (cache, {data}) => {
+ const existingTodos = cache.readQuery({ query: GET_MY_TODOS });
+ const newTodos = existingTodos.todos.filter(t => (!t.is_completed));
+ cache.writeQuery({query:GET_MY_TODOS, data: {todos: newTodos}});
+ }
+ });
}

That's a wrap of the todo app.

Close

Get Started with GraphQL Now

Hasura Cloud gives you a fully managed, production ready GraphQL API as a service to help you build modern apps faster.
Ready to get started?
Start for free on Hasura Cloud or you could contact our sales team for a detailed walk-through on how Hasura may benefit your business.
Stay in the know
Sign up for full access to our community highlights, new features, and occasional baby animal gifs! Oh, and we have a strict no-spam rule. โœŒ๏ธ