loading...
Cover image for Writing Mutations with Apollo Client

Writing Mutations with Apollo Client

ayemitibo profile image Ayemitibo Abiodun Updated on ・2 min read

What is Apollo Client?

Apollo Client is a comprehensive state management library for JavaScript that enables you to manage both local and remote data with GraphQL. Use it to fetch, cache, and modify application data, all while automatically updating your UI. Mostly, while working with apollo I don't think you need any other state management library like(vuex or redux)

what are mutations and queries?

we all know while working with REST APIs we have the basic request we make which are 'GET, POST, PUT, PATCH ...etc', but when making requests to a graphql endpoint we have two major requests which are QUERIES AND MUTATIONS. A QUERY is any request that reads from the server i.e getting all post from an API endpoint will require us to use a query and MUTATION on the other end is any request that writes to the server i.e saving a post to an API endpoint will require you to write a mutation.

How To Write A Simple Mutation

let's assume we have an API Endpoint to create a blog post(mutation)
Create Blog Post

as you can see from the image above we have the createPost mutation takes an 'input' object that contains 'data' and the data property takes post_title, post_date, post_detail, etc. You will notice each property on the data object has a type of property that can be String, String!, ID, Date, Upload, and Enum types also which won't cover in the article.

Our Mutation

mutation createPost(
    $post_title: String
    $post_date: Date
    $post_detail: String
    $post_image: ID
  ) {
    createPost(
      input: {
        data: {
          post_title: $post_title
          post_detail: $post_detail
          post_date: $post_date
          post_image: $post_image
        }
      }
    ) {
      post {
        id
      }
    }
  }`
Enter fullscreen mode Exit fullscreen mode

How to Write multiple Mutations

mutations fields run in series i.e the first mutation must finish before the second starts. Let's assume we have a button that does two things it creates a post and also creates a post collection.
This is the playground
Create Blog Post

Mutation

export const CREATE_POST = gql`
  mutation createPost(
    $post_title: String
    $post_date: Date
    $post_detail: String
    $post_image: ID
    $name: String
  ) {
    createPost(
      input: {
        data: {
          post_title: $post_title
          post_detail: $post_detail
          post_date: $post_date
          post_image: $post_image
        }
      }
    ) {
      post {
        id
      }
    }
    createCollection(input: { data: { name: $name } }) {
      collection {
        name
      }
    }
  }
`;
Enter fullscreen mode Exit fullscreen mode

you can pull this Vue repo to check the full source code

Discussion

pic
Editor guide