变更和更新缓存

现在让我们来做整合的部分。打开src/components/Todo/TodoItem.js并在其他导入的下方添加以下代码:

+ import { gql } from "@apollo/client";

让我们定义graphql 变更以更新待办事项的已完成状态

githubsrc/components/Todo/TodoItem.js
const TodoItem = ({index, todo}) => {
const removeTodo = (e) => {
e.preventDefault();
e.stopPropagation();
};
+ const TOGGLE_TODO = gql`
+ mutation toggleTodo ($id: Int!, $isCompleted: Boolean!) {
+ update_todos(where: {id: {_eq: $id}}, _set: {is_completed: $isCompleted}) {
+ affected_rows
+ }
+ }
+ `;
const toggleTodo = () => {};
return (
...
);
};
export default TodoItem;

Apollo 使用变更 React hook

我们需要使用 useMutationReact hook 来进行变更。

import React from 'react';
- import { gql } from "@apollo/client";
+ import { useMutation, gql } from "@apollo/client";
const TodoItem = ({index, todo}) => {
const removeTodo = (e) => {
e.preventDefault();
e.stopPropagation();
};
const TOGGLE_TODO = gql`
mutation toggleTodo($id: Int!, $isCompleted: Boolean!) {
update_todos(
where: { id: { _eq: $id } }
_set: { is_completed: $isCompleted }
) {
affected_rows
}
}
`;
+ const [toggleTodoMutation] = useMutation(TOGGLE_TODO);
return (
...
);
};
export default TodoItem;

我们已经有了关于更改处理程序切换待办事项的输入。让我们更新函数,以使用变toggleTodoMutation更函数。

const toggleTodo = () => {
+ toggleTodoMutation({
+ variables: {id: todo.id, isCompleted: !todo.is_completed},
+ optimisticResponse: true,
+ });
};

上述代码将只是进行变更,更新数据库中待办事项的是_已完成属性。为了更新缓存,我们将再次使用update函数来修改缓存。我们需要在修改前从缓存中获取当前的待办事项列表。因此让我们导入查询。

+ import {GET_MY_TODOS} from './TodoPrivateList';

现在让我们添加update函数的代码。

const toggleTodo = () => {
toggleTodoMutation({
variables: {id: todo.id, isCompleted: !todo.is_completed},
optimisticResponse: true,
+ update: (cache) => {
+ const existingTodos = cache.readQuery({ query: GET_MY_TODOS });
+ const newTodos = existingTodos.todos.map(t => {
+ if (t.id === todo.id) {
+ return {...t, is_completed: !t.is_completed};
+ } else {
+ return t;
+ }
+ });
+ cache.writeQuery({
+ query: GET_MY_TODOS,
+ data: {todos: newTodos}
+ });
+ }
});
};

我们正在使用缓存获取现有的待办事项,cache.readQuery并更新已更新的待办事项的是_已完成值。

最后,我们使用cache.writeQuery将更新的待办事项列表写入缓存。

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