1

I recently came across with this “Simplify your React components with Apollo and Recompose” @stubailo https://dev-blog.apollodata.com/simplify-your-react-components-with-apollo-and-recompose-8b9e302dea51

It shows how you can do GraphQL queries with recompose. I was wondering if anyone can provide an example of doing a GraphQL mutation with recompose. Like submitting a form or something similar.

Much appreciated.

1 Answers1

2

Compose usage with mutations is pretty much the same as with queries. Simple (untested) example with a form below. The form component has one textbox and receives a submitForm property. This property is mapped to the UpdateThing mutation through the apollo HoC wrapper and gets passed the necessary arguments.

Form.jsx

export default class Form extends React.Component {
  state = {
    name: this.props.name
  };

  handleSubmit = (e) => {
    e.preventDefault();
    this.props.submitForm(this.props.id, this.state.name);
  };

  handleChangeName = (e) => {
    this.setState({
      name: e.target.value
    });
  };

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <input type="text" id="name" name="name" onChange={this.handleChangeName} value={this.state.name} />
        <button type="submit">Submit</button>
      </form>
    );
  }
}

FormContainer.jsx

const withQuery = ... // Assume query code here

const withUpdateThing = graphql(gql`
  mutation UpdateThing($id: ID!, $name: String!) {
    updateThing(id: $id, name: $name) {
      id
      name
    }
  }
`, {
  props: ({ mutate }) => ({
    submitForm: (id, name) => mutate({ variables: { id, name } })
  })
});

export default compose(withQuery, withUpdateThing)(Form);

Which can then be used by simply doing <FormContainer id={1} />. withQuery injects the name prop, withUpdateThing injects the submitForm(id, name) prop.

pleunv
  • 389
  • 1
  • 5
  • Thanks for the answer. But I didn't ask how to do GraphQL mutations in conjugation with Apollo's `compose`. I want to do a mutation (a form submit) using `recompose.js`. I want my `Form` to be a pure component, handle state with recompose's `withState` and state handlers with `withHandlers` and compose using recompose's `compose`. – cannot_mutably_borrow Feb 23 '17 at 03:07
  • Then this is not an apollo-client question. I think the examples here should be pretty clear: https://github.com/acdlite/recompose – pleunv Feb 23 '17 at 08:16
  • @pleuv I ended up using your solution for time being till I figure out recompose. Thanks muchly! :) – cannot_mutably_borrow Feb 24 '17 at 03:54
  • @YounisShah: and have you figured out? i'm standing at excactly the same point right now ;-) – hereandnow78 Mar 31 '17 at 20:36