Created
February 7, 2018 02:39
-
-
Save thomasdashney/a214175b848efac93a95ae0490040d6b to your computer and use it in GitHub Desktop.
Mutation component POC
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Mutation extends Component { | |
constructor (props, context) { | |
super(props, context) | |
if (!context.client) throw new Error('<ApolloProvider /> required for mutation') | |
this.client = context.client | |
} | |
static contextTypes = { | |
client: PropTypes.object.isRequired | |
} | |
static propTypes = { | |
children: PropTypes.func.isRequired, | |
mutation: PropTypes.object.isRequired | |
} | |
state = { | |
loading: false, | |
result: undefined, | |
error: null | |
} | |
mutate = async (options = {}) => { | |
if (this.state.loading) return // support a single concurrent mutation | |
const optionWhitelist = ['mutation', 'variables', 'errorPolicy'] | |
const params = optionWhitelist.reduce((prev, optionName) => { | |
return Object.assign({}, prev, { | |
[optionName]: options[optionName] || this.props[optionName] | |
}) | |
}, {}) | |
this.setState({ | |
loading: true, | |
error: null, | |
result: undefined | |
}) | |
try { | |
let result = await this.client.mutate(params) | |
this.setState({ | |
loading: false, | |
result | |
}) | |
} catch (error) { | |
this.setState({ | |
loading: false, | |
error | |
}) | |
} | |
} | |
render () { | |
return this.props.children({ | |
mutate: this.mutate, | |
loading: this.state.loading, | |
result: this.state.result, | |
error: this.state.error | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment