2

I am considering using React Relay or the Apollo Client. I like the idea of GraphQL as a query language that can be executed against any API or data store.

However, I am surprised by the need to manually (and imperatively) update the store/cache after a simple mutation such as adding a todo item to a list. Here is the documentation for the updater/update functions:

http://facebook.github.io/relay/docs/en/mutations.html https://www.apollographql.com/docs/react/essentials/mutations.html

Why is a user-defined updater function required?

Specifically, why must I write an updater function to handle running these two GraphQL queries in sequence?

//Create todo item
mutation createTodo($input: TodoInput!) {
    createTodo(input: $input) {
        id
        name
        desc
    }
}

mutationVariables = { input: { name: 'Shopping', desc: 'Get groceries' }};


//Select all todos
query {
    todos {
        id
        name
        desc
    }
}  

Why would the todos query not return the new todo item automatically? That is the POINT of a declarative query language IMO.

Corey Quillen
  • 1,566
  • 4
  • 24
  • 52

1 Answers1

0

The idea behind updating the local cache is to minimize the amount of data being passed between the client and the server.

Updating the local cache manually is entirely up to you. You can absolutely program your mutation to return the new or all todo's then it will update your local cache. (it will be slower than manually updating since you will need to wait for the response.) There are some good use cases for manually updating vs waiting for the response from the server

With apollo you can also turn off local cache and just use "network-only" as your fetch policy.

wrod7
  • 179
  • 10
  • Forget optimistic vs pessimistic updates for a moment. The query after the mutation should return the new todo automatically regardless of the response right? Even if that means the query is asynchronous and must go to the server first. – Corey Quillen Sep 06 '18 at 14:20
  • it should yes, you can setup your mutation with a refetch query to automatically run the query after the mutation. – wrod7 Sep 06 '18 at 15:08
  • I am already running a query after the mutation above. Are you saying that I need to declare another query: a "refetch" query? – Corey Quillen Sep 07 '18 at 02:41
  • its just another way for refetching the new "todos" read this example here: https://github.com/apollographql/apollo-client/blob/master/docs/source/api/react-apollo.md#optionsrefetchqueries – wrod7 Sep 07 '18 at 14:37