<commit_before>---
title: Mutations
---

In addition to fetching data using queries, Apollo also helps you handle GraphQL mutations. In GraphQL, mutations are identical to queries in syntax, the only difference being that you use the keyword `mutation` instead of `query` to indicate that the root fields on this query are going to be performing writes to the backend.

```js
mutation {
  submitRepository(repoFullName: "apollographql/apollo-client") {
    id
    repoName
  }
}
```

GraphQL mutations represent two things in one query string:

1. The mutation field name with arguments, `submitRepository`, which represents the actual operation to be done on the server.
2. The fields you want back from the result of the mutation to update the client, in this case `{ id, repoName }`.

The above mutation will submit a new GitHub repository to GitHunt, saving an entry to the database. The result might be:

```
{
  "data": {
    "submitRepository": {
      "id": "123",
      "repoName": "apollographql/apollo-client"
    }
  }
}
```

When we use mutations in Apollo, the result is typically integrated into the cache automatically [based on the id of the result](cache-updates.html#dataIdFromObject), which in turn updates the UI automatically, so we often don't need to explicitly handle the results. In order for the client to correctly do this, we need to ensure we select the necessary fields in the result. One good strategy can be to simply ask for any fields that might have been affected by the mutation. Alternatively, you can use [fragments](fragments.html) to share the fields between a query and a mutation that updates that query.

<h2 id="basics">Basic mutations</h2>

Using `graphql` with mutations makes it easy to bind actions to your components. Unlike queries, which provide a complicated object with lots of metadata and methods, mutations provide only a simple function to the wrapped component, in a prop called `mutate`.

```js
import React, { Component } from 'react';
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';

class NewEntry extends Component { ... }

const submitRepository = gql`
  mutation submitRepository {
    submitRepository(repoFullName: "apollographql/apollo-client") {
      createdAt
    }
  }
`;

const NewEntryWithData = graphql(submitRepository)(NewEntry);
```

The component created above will recieve a prop called `mutate` which is a function that returns a promise of the mutation result.

<h2 id="calling-mutations">Calling mutations</h2>

Most mutations will require arguments in the form of query variables, and you may wish to also provide other options as well. [See the complete set of mutation options in the API docs.](#graphql-mutation-options)

The simplest option is to directly pass options to the default `mutate` prop when you call it in the wrapped component:

```js
import React, { Component } from 'react';
import { gql, graphql } from 'react-apollo';

class NewEntry extends Component {
  onClick() {
    this.props.mutate({
      variables: { repoFullName: 'apollographql/apollo-client' }
    })
      .then(({ data }) => {
        console.log('got data', data);
      }).catch((error) => {
        console.log('there was an error sending the query', error);
      });
  }

  render() {
    return <div onClick={this.onClick.bind(this)}>Click me</div>;
  }
}

const submitRepository = gql`
  mutation submitRepository($repoFullName: String!) {
    submitRepository(repoFullName: $repoFullName) {
      createdAt
    }
  }
`;

const NewEntryWithData = graphql(submitRepository)(NewEntry);
```

<h3 id="custom-arguments">Custom arguments</h3>

While the above approach with the default prop works just fine, typically you'd want to keep the concern of formatting the mutation options out of your presentational component. The best way to do this is to use the [`props`](setup.html#graphql-config-props) config to wrap the mutation in a function that accepts exactly the arguments it needs:

```js
const NewEntryWithData = graphql(submitRepository, {
  props: ({ mutate }) => ({
    submit: (repoFullName) => mutate({ variables: { repoFullName } }),
  }),
})(NewEntry);
```

Here's that in context with a component, which can now be much simpler because it just needs to pass one argument:

```js
import React, { Component } from 'react';
import { gql, graphql } from 'react-apollo';

const NewEntry = ({ submit }) => (
  <div onClick={() => submit('apollographql/apollo-client')}>
    Click me
  </div>
);

const submitRepository = gql`...`; // Same query as above

const NewEntryWithData = graphql(submitRepository, {
  props: ({ mutate }) => ({
    submit: (repoFullName) => mutate({ variables: { repoFullName } }),
  }),
})(NewEntry);
```

Note that, in general, you don't need to use the results from the mutation callback directly. Instead you should usually rely on Apollo's id-based cache updating to take care of it for you. If that doesn't cover your needs, there are [several different options for updating the store after a mutation](cache-updates.html). That way, you can keep your UI components as stateless and declarative as possible.

<h2 id="multiple-mutations">Multiple mutations</h2>

If you need more than one mutation on a component, you make a graphql container for each:

```js
const ComponentWithMutations =
  graphql(submitNewUser, { name: 'newUserMutation' })(
    graphql(submitRepository, { name: 'newRepositoryMutation' })(Component)
  )
```

Make sure to use the [`name` option on the `graphql()` container](setup#graphql-config-name) to name the provided prop, so that the two containers don't both try to name their function `mutate`.

If you want a better syntax for the above, consider using [`compose`](setup#compose):

```js
import { compose } from 'react-apollo';

const ComponentWithMutations = compose(
  graphql(submitNewUser, { name: 'newUserMutation' }),<commit_msg>fix link to cache updates<commit_after>---
title: Mutations
---

In addition to fetching data using queries, Apollo also helps you handle GraphQL mutations. In GraphQL, mutations are identical to queries in syntax, the only difference being that you use the keyword `mutation` instead of `query` to indicate that the root fields on this query are going to be performing writes to the backend.

```js
mutation {
  submitRepository(repoFullName: "apollographql/apollo-client") {
    id
    repoName
  }
}
```

GraphQL mutations represent two things in one query string:

1. The mutation field name with arguments, `submitRepository`, which represents the actual operation to be done on the server.
2. The fields you want back from the result of the mutation to update the client, in this case `{ id, repoName }`.

The above mutation will submit a new GitHub repository to GitHunt, saving an entry to the database. The result might be:

```
{
  "data": {
    "submitRepository": {
      "id": "123",
      "repoName": "apollographql/apollo-client"
    }
  }
}
```

When we use mutations in Apollo, the result is typically integrated into the cache automatically [based on the id of the result](cache-updates.html#dataIdFromObject), which in turn updates the UI automatically, so we often don't need to explicitly handle the results. In order for the client to correctly do this, we need to ensure we select the necessary fields in the result. One good strategy can be to simply ask for any fields that might have been affected by the mutation. Alternatively, you can use [fragments](fragments.html) to share the fields between a query and a mutation that updates that query.

<h2 id="basics">Basic mutations</h2>

Using `graphql` with mutations makes it easy to bind actions to your components. Unlike queries, which provide a complicated object with lots of metadata and methods, mutations provide only a simple function to the wrapped component, in a prop called `mutate`.

```js
import React, { Component } from 'react';
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';

class NewEntry extends Component { ... }

const submitRepository = gql`
  mutation submitRepository {
    submitRepository(repoFullName: "apollographql/apollo-client") {
      createdAt
    }
  }
`;

const NewEntryWithData = graphql(submitRepository)(NewEntry);
```

The component created above will recieve a prop called `mutate` which is a function that returns a promise of the mutation result.

<h2 id="calling-mutations">Calling mutations</h2>

Most mutations will require arguments in the form of query variables, and you may wish to also provide other options as well. [See the complete set of mutation options in the API docs.](#graphql-mutation-options)

The simplest option is to directly pass options to the default `mutate` prop when you call it in the wrapped component:

```js
import React, { Component } from 'react';
import { gql, graphql } from 'react-apollo';

class NewEntry extends Component {
  onClick() {
    this.props.mutate({
      variables: { repoFullName: 'apollographql/apollo-client' }
    })
      .then(({ data }) => {
        console.log('got data', data);
      }).catch((error) => {
        console.log('there was an error sending the query', error);
      });
  }

  render() {
    return <div onClick={this.onClick.bind(this)}>Click me</div>;
  }
}

const submitRepository = gql`
  mutation submitRepository($repoFullName: String!) {
    submitRepository(repoFullName: $repoFullName) {
      createdAt
    }
  }
`;

const NewEntryWithData = graphql(submitRepository)(NewEntry);
```

<h3 id="custom-arguments">Custom arguments</h3>

While the above approach with the default prop works just fine, typically you'd want to keep the concern of formatting the mutation options out of your presentational component. The best way to do this is to use the [`props`](setup.html#graphql-config-props) config to wrap the mutation in a function that accepts exactly the arguments it needs:

```js
const NewEntryWithData = graphql(submitRepository, {
  props: ({ mutate }) => ({
    submit: (repoFullName) => mutate({ variables: { repoFullName } }),
  }),
})(NewEntry);
```

Here's that in context with a component, which can now be much simpler because it just needs to pass one argument:

```js
import React, { Component } from 'react';
import { gql, graphql } from 'react-apollo';

const NewEntry = ({ submit }) => (
  <div onClick={() => submit('apollographql/apollo-client')}>
    Click me
  </div>
);

const submitRepository = gql`...`; // Same query as above

const NewEntryWithData = graphql(submitRepository, {
  props: ({ mutate }) => ({
    submit: (repoFullName) => mutate({ variables: { repoFullName } }),
  }),
})(NewEntry);
```

Note that, in general, you don't need to use the results from the mutation callback directly. Instead you should usually rely on Apollo's id-based cache updating to take care of it for you. If that doesn't cover your needs, there are [several different options for updating the store after a mutation](../features/cache-updates.html). That way, you can keep your UI components as stateless and declarative as possible.

<h2 id="multiple-mutations">Multiple mutations</h2>

If you need more than one mutation on a component, you make a graphql container for each:

```js
const ComponentWithMutations =
  graphql(submitNewUser, { name: 'newUserMutation' })(
    graphql(submitRepository, { name: 'newRepositoryMutation' })(Component)
  )
```

Make sure to use the [`name` option on the `graphql()` container](setup#graphql-config-name) to name the provided prop, so that the two containers don't both try to name their function `mutate`.

If you want a better syntax for the above, consider using [`compose`](setup#compose):

```js
import { compose } from 'react-apollo';

const ComponentWithMutations = compose(
  graphql(submitNewUser, { name: 'newUserMutation' }),
{'fraction_non_alphanumeric': 0.0967032967032967, 'fraction_numerical': 0.002197802197802198, 'mean_word_length': 4.331680937359171, 'pattern_counts': {'":': 8, '<': 27, '<?xml version=': 0, '>': 43, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5807944', 'n_tokens_mistral': 3304, 'n_tokens_neox': 3183, 'n_words': 1434}