Mutation and update cache

Now let's do the integration part. Open src/components/Todo/TodoItem.svelte and add the following code to define the delete mutation

githubsrc/components/Todo/TodoItem.svelte
+ const REMOVE_TODO = gql`
+ mutation removeTodo($id: Int!) {
+ delete_todos(where: { id: { _eq: $id } }) {
+ affected_rows
+ }
+ }
+ `;
+
+ const removeTodoMutation = mutation(REMOVE_TODO);

We have a function defined to handle the button click to remove a todo. Let's update the function to use removeTodoMutation mutate function.

const removeTodo = (e) => {
e.preventDefault();
e.stopPropagation();
+ removeTodoMutation({
+ variables: {id: todo.id},
+ optimisticResponse: true,
+ update: (cache) => {
+ const existingTodos = cache.readQuery({ query: GET_MY_TODOS });
+ const newTodos = existingTodos.todos.filter(t => (t.id !== todo.id));
+ cache.writeQuery({
+ query: GET_MY_TODOS,
+ data: {todos: newTodos}
+ });
+ }
+ });
};
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. โœŒ๏ธ