Search code examples
graphqlapolloapollo-client

Trigger a GraphQL mutation not using the Mutation component


I'm trying to send a mutation query to a GraphQL server that uses Apollo.

However, I only see the only way to achieve this is by using a Mutation component. https://www.apollographql.com/docs/react/essentials/mutations/#the-mutation-component

Is there an easy way I can send mutations doing something like this?

import gql from 'graphql-tag';

client.query({
  query: gql`
    query TodoApp {
      todos {
        id
        text
        completed
      }
    }
  `,
})
  .then(data => console.log(data))
  .catch(error => console.error(error));

Solution

  • You don't need the mutation component to trigger a mutation.

    You can just pass the mutation in the gql query object, something like:

    client.query({
      query: gql`
        mutation MyMutation {
          doSomthing {
            id
            returnedValue1
          }
        }
      `,
    })
    .then(data => console.log(data))
    .catch(error => console.error(error));