Mutation and update cache

Now let's do the integration part.

Firstly, let's define the graphql mutation to update the completed status of the todo. Open src/ and add the following code below everything else:
// GraphQL mutation for toggling a todo
module ToggleMyTodo = [%graphql
mutation toggleTodo ($id: Int!, $isCompleted: Boolean!) {
update_todos(where: {id: {_eq: $id}}, _set: {is_completed: $isCompleted}) {
returning {
module ToggleMyTodoMutation = ReasonApollo.CreateMutation(ToggleMyTodo);

In the previous section, we performed insert mutation. We will follow the same steps for toggling todos between complete and active by using the update mutation.

Go to src/todo/, and wrap the checkbox with the ToggleMyTodoMutation component that we defined above.
+ ...{
+ (mutate, _) => {
+ let toggleTodo = GraphQLQueries.ToggleMyTodo.make(~id=todo##id, ~isCompleted=!todo##is_completed, ());
+ onChange={
+ event => {
+ mutate(
+ ~variables=toggleTodo##variables,
+ ()
+ ) |> ignore;
+ }
+ }
+ }
+ }

The above code will just make a mutation, updating the todo's is_completed property in the database. If you see in the above code snippet, we are not doing anything to updating the cache, but if you try it out in the UI, the mutation succeeds and the UI is also updated.

This happens because, in case of update mutation, apollo client tries to keep the cache fresh by performing automatic updates using the following strategy:

  1. It looks at the id and __typename of the mutation response
  2. It looks for the objects in the cache that have id and __typename similar to the ones in the mutation response.
  3. If there is a match, it updates the cache with the data from the mutation response