Skip to content

Instantly share code, notes, and snippets.

@SachaG
Last active December 24, 2016 09:29
Show Gist options
  • Save SachaG/c91ff7c95593c6cc34a9c4346558e4c8 to your computer and use it in GitHub Desktop.
Save SachaG/c91ff7c95593c6cc34a9c4346558e4c8 to your computer and use it in GitHub Desktop.
// wrapper
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
export default function withMutation(name) {
return graphql(gql`
mutation ${name}($vars: JSON) {
${name}(vars: $vars)
}
`, {
props: ({ownProps, mutate}) => ({
[name]: vars => {
return mutate({
variables: { vars },
});
}
}),
});
}
// component
import { withMutation } from 'withMutation.js';
const MyComponent extends Component {
fetchMetaData() {
this.props.getMetaData({url: this.props.url}) /* get url from somewhere */
.then(result => {/* do something with the result */})
.catch(error => {/* do something with the error */})
},
render() {
return (/* render component here */)
}
}
export default withMutation('getMetaData')(MyComponent);
// schema
const schema = [`
type Mutation {
getMetaData(
vars: JSON
) : JSON
}
`];
// resolver
const rootResolvers = {
Mutation: {
getMetaData(root, { vars: { url } }, context) {
const data = ... // make some kind of API call
return data;
},
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment