2

Since version 2.1 Apollo Client uses React's render props pattern.

On the official Apollo Client documentation variables are passed as parameter to the mutation function:

addTodo({ variables: { type: input.value } });

however various tutorials, including How to GraphQL, pass them as props:

<Mutation mutation={POST_MUTATION} variables={{ description, url }}>

What are there reasons for choosing one way or the other?

1
  • 1
    They're not mutually exclusive. Variables passed as props can be overridden when you call the mutate function that's handed to you in the render props, so you could view the second form as providing default values. In practice, I've never used the second form, I usually find myself wrapping the Mutation component around, say, a form, and calling the mutate function when the form is submitted. But there could be some use for passing the variables as props when those are known beforehand and user input is not required or already known, for example a logout mutation, or a "like" action. Commented Feb 7, 2019 at 17:20

1 Answer 1

1

You can safely use either method of passing variables to the mutation.

Most of the time I would use the variables prop to set the variables since this is pretty clear and neat.

An instance where you might want to use the other method is when calling the mutation method from a child component - where the variables are also contained in that child component.

To follow on from the example code you gave above: Imagine an array of components on a ToDo list where each has an input but calls a single mutation (located in the parent component). It would be easier to call the mutation from inside each child components eg:

updateToDoItem({variables: {id: this.props.id, text: this.state.text}})

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.