变更和更新缓存
现在让我们进行集成部分。打开src/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+ }+ }+ `;+ const [removeTodoMutation] = useMutation(REMOVE_TODO);
我们定义了一个函数来处理按钮单击以删除待办事项。让我们使用removeTodoMutation
变更函数来更新这个函数。
const removeTodo = (e) => {e.preventDefault();e.stopPropagation();+ removeTodoMutation({+ variables: {id: todo.id},+ optimisticResponse: true,+ 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}+ });+ }+ });};
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