キャッシュのミューテーションと更新
src/components/Todo/TodoPrivateList.js
を開いて、 useMutation
Reactフックをインポートしてから、一括削除mutationを追加します。
import React, { Fragment, useState } from "react";- import { gql } from '@apollo/client';- import { useQuery } from '@apollo/client';+ import { useQuery, useMutation, gql } from "@apollo/client";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 }) {idtitlecreated_atis_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+ }+ }+ `;
以下に示すように useMutation
Reactフックを使って、 clearCompleted
関数を更新します。
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}});+ }+ });}
todoアプリのラップは以上です。
Did you find this page helpful?
Start with GraphQL on Hasura for Free
- Build apps and APIs 10x faster
- Built-in authorization and caching
- 8x more performant than hand-rolled APIs