DEV Community

Cover image for Optimistic UI Trick Revealed!
ghack.dev
ghack.dev

Posted on

Optimistic UI Trick Revealed!

Fake it, 'til you make it.

Suddenly I remember that quote when I'm talking about Optimistic UI. Before I understand what Optimistic UI is, I just wondering that how a response could be that fast. 😳 For example, look at Instagram like UI.

optimistic-ui-apollo-graphql-instagram

There is no boring loading icon. When we press the like button, it will immediately liked the post. That's awesome right? 😲

When a Magician 🎩 performs a trick, we could be easily amazed until someone revealed the trick.

So, How Optimistic UI works?

Let's reveal the secret behind the Optimistic UI trick.

Optimistic UI is a pattern that you can use to simulate the results of a mutation and update the UI even before receiving a response from the server. Once the response is received from the server, the optimistic result is thrown away and replaced with the actual result. -- Apollo GraphQL

"Simulate the results" means that we need to fake the response first, before we receive the real one. That's it. 💁‍♂️

Example

We could implement this pattern easily using Apollo Client. This is one of the benefits of using GraphQL because the request and response are defined earlier in the Query and Mutation schema, we could easily fake the response while ensuring that the data becomes consistent with the actual response when it arrives.

const LIKE_POST = gql`
  mutation LikePost($postID: ID!) {
    likePost(postID: $postID) {
      id
      __typename
      likers
    }
  }
`

const Posts = () => {
  const username = useSelector(state => state.auth.username)
  const [mutate] = useMutation(LIKE_POST)
  return (
    <Comment
      updateComment={({ id, likers }) =>
        mutate({
          variables: { postID: id },
          optimisticResponse: {
            __typename: "Mutation",
            likePost: {
              id,
              __typename: "Post",
              likers: [...likers, username]
            }
          }
        })
      }
    />
  )
}

Now, this trick couldn't amazed us anymore. 😅

Top comments (1)

Collapse
 
salimkafin profile image
kafin

but how you process that optimisticResponse? like reading it?