Reputation: 689
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.
Upvotes: 1
Views: 965
Reputation: 388
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.
Upvotes: 2