Mutation and update cache

Now let's do the integration part. Open Todo/TodoVC.swift and add the following code to define the delete mutation

githubTodo/TodoVC.swift
// Remove Todos from cloud
private func removeTodosMutationCloud(indexPath: IndexPath!){
let id = filteredTodos[indexPath.row].id
apollo.perform(mutation: RemoveTodoMutation(id: id)) { (result, error) in
guard let data = result?.data else { return }
if data.deleteTodos?.affectedRows == 1 {
let index = self.filteredTodos.firstIndex{$0.id == id}!
self.todos.remove(at: index)
self.filteredTodos.remove(at: index)
// Remove from local
self.removeTodosMutationLocal(id: id)
DispatchQueue.main.async {
self.toggleCompleteAction()
// Delete the table view row
self.todoTable.deleteRows(at: [indexPath], with: .fade)
}
}
}
}

Also, the function to remove todos from the localcache,

// Remove Todos to local cache
private func removeTodosMutationLocal(id: Int){
_ = apollo.store.withinReadWriteTransaction{ transaction in
let query = GetMyTodosQuery()
try transaction.update(query: query) { (data: inout GetMyTodosQuery.Data) in
let todos = data.todos
if ( id == -1 ) {
data.todos = data.todos.filter({!$0.isCompleted})
} else {
guard let index = todos.firstIndex(where: {$0.id == id}) else {return}
data.todos.remove(at: index)
}
_ = self.apollo.store.load(query: query).andThen({ (data) in
// Watch your data in local cache
// dump(data.data?.resultMap)
// Look for errors
// dump(data.errors)
})
}
}
}
}

We have a function defined to handle the swipe to remove a todo. Let's update the function.

// Swipe Row to Delete
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// remove the item from the data model
- self.removeTodos(indexPath: indexPath.row)
+ self.removeTodosMutationCloud(indexPath: indexPath)
}
}