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
// Remove Todos from cloudprivate func removeTodosMutationCloud(indexPath: IndexPath!){let id = filteredTodos[indexPath.row].idapollo.perform(mutation: RemoveTodoMutation(id: id)) { (result, error) inguard 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 localself.removeTodosMutationLocal(id: id)DispatchQueue.main.async {self.toggleCompleteAction()// Delete the table view rowself.todoTable.deleteRows(at: [indexPath], with: .fade)}}}}
Also, the function to remove todos from the localcache,
// Remove Todos to local cacheprivate func removeTodosMutationLocal(id: Int){_ = apollo.store.withinReadWriteTransaction{ transaction inlet query = GetMyTodosQuery()try transaction.update(query: query) { (data: inout GetMyTodosQuery.Data) inlet todos = data.todosif ( 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 Deletefunc 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)}}
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