Search⌘ K
AI Features

GraphQL Mutation with Apollo Client in React

Explore how to use mutations in React applications with Apollo Client by implementing repository starring, unstarring, and watching features via GitHub's GraphQL API. Understand how to pass variables, trigger mutations, handle results, and update the UI based on Apollo Client's cache integration.

We'll cover the following...

The previous lessons have taught you how to query data with React Apollo and the Apollo Client. In this lesson, you will learn about mutations. As in other applications before, we have implemented starring a repository with GitHub’s exposed addStar mutation.

The mutation starts out with a variable to identify the repository to be starred. We haven’t used a variable in Query component yet, but the following mutation works the same way, which can be defined in the src/Repository/RepositoryItem/index.js file.

Node.js
import React from 'react';
import gql from 'graphql-tag';
...
const STAR_REPOSITORY = gql`
mutation($id: ID!) {
addStar(input: { starrableId: $id }) {
starrable {
id
viewerHasStarred
}
}
}
`;
...

The mutation definition takes the id variable as input for the addStar mutation. As before, we can decide what should be returned in case of a successful mutation and incorporate that into our query. Next, we will use a Mutation component that represents the ...