Learn Relay/
← 0406 →

05 - useMutation

Learn how to use useMutation to modify GraphQL data.

Exercise

  • get your user token (see Your user token below, this replaces pnpm get-token) and put the token on the Authorization header on the Network Layer (relay/fetchGraphQL.tsx, use getToken from relay/getToken.tsx)
  • create a PostLike mutation in PostLikeMutation.tsx and use it with useMutation to like a Post when clicking the like button

Extras

  • implement the PostUnLike mutation (clicking the button of a liked post should unlike it)
  • add an optimisticResponse to provide a fast feedback to the user

Code Helpers

PostLikeMutation

mutation PostLikeMutation($input: PostLikeInput!) {
  PostLike(input: $input) {
    success
    error
    post {
      meHasLiked
      likesCount
    }
  }
}
Your user token

The replacement for pnpm get-token. It logs you in as Sibelius Seraphini.

JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6InUxIn0.relay-workshop
Next: Mutation updater →
Loading editor…
localhost:7500 · in-browser GraphQL server
Checks verify your solution against the running app.
  • ○The network layer sends the Authorization header
  • ○Clicking the like button sends PostLikeMutation
  • ○The like count and meHasLiked are updated in the store and UI
  • ○(extra) Clicking a liked post sends PostUnLikeMutation
  • ○(extra) Optimistic response updates the UI before the server answers