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.

Close

Get Started with GraphQL Now

Hasura Cloud gives you a fully managed, production ready GraphQL API as a service to help you build modern apps faster.
Ready to get started?
Start for free on Hasura Cloud or you could contact our sales team for a detailed walk-through on how Hasura may benefit your business.
Stay in the know
Sign up for full access to our community highlights, new features, and occasional baby animal gifs! Oh, and we have a strict no-spam rule. โœŒ๏ธ