1

Is the following example possible with apollo-client?

For an example an easy ToDo application and bad internet connection:

  1. no internet connection
  2. (1. mutation) create a new todo
  3. (1. mutation => optimistic update) show the new todo (local tmp-ID)
  4. (2. mutation) check the new todo as completed (with the tmp-ID)
  5. (2. mutation => optimistic update) show todo as completed
  6. now connected to the server
  7. ???

can Apollo client replace the tmp-ID for the correct todo or how can I do it manually?

ManAnRuck
  • 234
  • 2
  • 10

1 Answers1

0

You can try this, but I don't think you will be able to retain the completed status of true on your server because you are sending a completeTodo mutation with a temporary id. There is now way for your server to know which todo you are referencing. Although this may give you two optimistic updates as you want.

const CREATE_TODO_MUTATION = gql`
  mutation createTodo($todoContent: String!) {
    createTodo(todoContent: $todoContent) {
      id
      createdAt
      content
      completed
    }
  }
`;

const COMPLETE_TODO_MUTATION = gql`
  mutation completeTodo($id: String!) {
    completeTodo(id: $id) {
      id
      createdAt
      content
      completed
    }
  }
`;

const TodosPageWithMutations = compose(
  graphql(CREATE_TODO_MUTATION, {
    props: ({ ownProps, mutate }) => ({
      createTodo: content => mutate({
        variables: { todoContent: content },
        optimisticResponse: {
          __typename: 'Mutation',
          createTodo: {
            __typename: 'Todo',
            id: createTempID(),
            content,
            completed: false,
            createdAt: new Date()
          }
        }
      }),
    }),
  }),
  graphql(COMPLETE_TODO_MUTATION, {
    props: ({ ownProps, mutate }) => ({
      completeTodo: todo => mutate({
        variables: { id: todo.id },
        optimisticResponse: {
          __typename: 'Mutation',
          completeTodo: {
            __typename: 'Todo',
            id: todo.id,
            content: todo.content,
            completed: true,
            createdAt: todo.createdAt
          }
        }
      }),
    }),
  })
)(TodosPage);
Mjuice
  • 1,288
  • 2
  • 13
  • 32