Mutation and update cache

Open src/components/Todo/TodoPrivateList.res and and add the following code to define the bulk delete mutation

githubsrc/components/Todo/TodoPrivateList.res
module ClearCompletedMutation = %graphql(`
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

let clearCompleted = _e =>
clearCompletedTodos(~update=({readQuery, writeQuery}, {data: _data}) => {
let existingTodos = readQuery(~query=module(TodosQuery), ())
switch existingTodos {
| Some(todosResult) =>
switch todosResult {
| Ok({todos}) => {
let newTodos = Js.Array2.filter(todos, t => !t.is_completed)
let _ = writeQuery(~query=module(TodosQuery), ~data={todos: newTodos}, ())
}
| _ => ()
}
| None => ()
}
}, ())->ignore

Let's pass optimistic response for instant UI update

let clearCompleted = _e =>
clearCompletedTodos(
+ ~optimisticResponse=_variables => {
+ delete_todos: Some(
+ (
+ {
+ affected_rows: 1,
+ __typename: "todos_mutation_response",
+ }: ClearCompletedMutation.ClearCompletedMutation_inner.t_delete_todos
+ ),
+ ),
+ },
~update=({readQuery, writeQuery}, {data: _data}) => {
let existingTodos = readQuery(~query=module(TodosQuery), ())
switch existingTodos {
| Some(todosResult) =>
switch todosResult {
| Ok({todos}) => {
let newTodos = Js.Array2.filter(todos, t => !t.is_completed)
let _ = writeQuery(~query=module(TodosQuery), ~data={todos: newTodos}, ())
}
| _ => ()
}
| None => ()
}
},
(),
)->ignore

That's a wrap of the todo app.

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