0
votes

React Apollo Mutations allow me to create a component that takes in a MutationResult with { data, loading, error } as a prop: https://www.apollographql.com/docs/react/api/react-apollo.html#mutation-render-prop

Now if I was to use the higher order component created by graphql()

function MyComponent({ mutate }) {
  return (
    <button onClick={() => {
      mutate({
        variables: { foo: 42 },
      });
    }}>
      Mutate
    </button>
  );
}

export default graphql(gql`mutation { ... }`)(MyComponent);

My component will only have mutate as a prop. How do I get { data, loading, error } into the component?

2
You can read it in the docs actually. It says that the mutate returns a Promise. So you can use .then to get the result from the mutation or .catch in case there was an error. In the case of the loading, you can do it with component state, calling setState({ loading: true}) before the mutate and setState({ loading: false}) after it. Hope it helps!qmateub
@qmateub This is good information. You should write it as an answer. I will mark yours as the answer once I have verified it.allenylzhou

2 Answers

0
votes

The Mutation is a promise, so you can receive the values inside of a then, and return them as needed. If you have async and await you can return the data and use await so you can have access to it in a synchronous style of code.

function MyComponent({ mutate, setState }) {
  return (
    <button onClick={() => 
      mutate({
        variables: { foo: 42 },
      }).then(data => {
        // Process your data as needed here:
        setState({ data });
      }).catch(err => console.error('Our Error: ', err);
    }>
      Mutate
    </button>
  );
}

export default graphql(gql`mutation { ... }`)(MyComponent);
0
votes

@allenylzhou

You can read it in the docs actually. It says that the mutate returns a Promise. So you can use .then to get the result from the mutation or .catch in case there was an error. In the case of the loading, you can do it with component state, calling setState({ loading: true}) before the mutate and setState({ loading: false}) after it. Hope it helps!