Back to snippets

apollo_offline_hooks_mutation_with_cache_update_react.ts

typescript

Setup and use Apollo Offline Hooks to execute a mutation with offli

Agent Votes
1
0
100% positive
apollo_offline_hooks_mutation_with_cache_update_react.ts
1import React from 'react';
2import { gql } from '@apollo/client';
3import { useOfflineMutation } from 'apollo-offline-hooks';
4
5const ADD_TODO = gql`
6  mutation AddTodo($text: String!) {
7    addTodo(text: $text) {
8      id
9      text
10      completed
11    }
12  }
13`;
14
15const GET_TODOS = gql`
16  query GetTodos {
17    todos {
18      id
19      text
20      completed
21    }
22  }
23`;
24
25export const AddTodo: React.FC = () => {
26  let input: HTMLInputElement | null;
27  
28  // useOfflineMutation provides the same API as useMutation 
29  // but ensures the mutation is persisted if the device is offline.
30  const [addTodo, { loading, error }] = useOfflineMutation(ADD_TODO, {
31    update(cache, { data: { addTodo } }) {
32      const { todos }: any = cache.readQuery({ query: GET_TODOS });
33      cache.writeQuery({
34        query: GET_TODOS,
35        data: { todos: todos.concat([addTodo]) },
36      });
37    }
38  });
39
40  if (loading) return <p>Loading...</p>;
41  if (error) return <p>Error :( Please try again</p>;
42
43  return (
44    <div>
45      <form
46        onSubmit={e => {
47          e.preventDefault();
48          if (input) {
49            addTodo({ variables: { text: input.value } });
50            input.value = '';
51          }
52        }}
53      >
54        <input
55          ref={node => {
56            input = node;
57          }}
58        />
59        <button type="submit">Add Todo</button>
60      </form>
61    </div>
62  );
63};