Mutaciones y actualización de la caché

Abra src/components/Todo/TodoPrivateList.js e importe el hook React useMutation y luego añada la mutación de borrado masivo.

githubsrc/components/Todo/TodoPrivateList.js
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 }
) {
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
+ }
+ }
+ `;

Utilice el hook React useMutation y actualice la función clearCompleted como sigue

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}});
+ }
+ });
}

Y eso es todo para la aplicación de tareas pendientes.

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