Skip to content

Instantly share code, notes, and snippets.

@relwell
Created February 6, 2019 00:08
Show Gist options
  • Save relwell/4fd07b241b3cb1f8cd6ce60246d7be4b to your computer and use it in GitHub Desktop.
Save relwell/4fd07b241b3cb1f8cd6ce60246d7be4b to your computer and use it in GitHub Desktop.
example graphql
import React from 'react';
import { compose, graphql } from 'react-apollo';
// i actually recommend .graphql files with the webpack loader from this library
import { gql } from 'graphql-tag';
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';
import CircularProgress from '@material-ui/core/CircularProgress';
const entryQuery = gql`
query lookupEntry($key: String!) {
lookupEntry(key:$key) {
value
}
}
`;
const entryMutation = gql`
mutation updateEntry($key: String!, $value: String!) {
updateEntry(input: { key: $key, value: $value }) {
value
})
}
`;
class SimpleFormWithGraphql extends React.Component
{
state = {
someValue: '',
loading: false,
}
changeInput = field => e => this.setState({ [field]: e.target.value });
onSubmit = async e => {
e.preventDefault();
const { updateMutation } = this.props;
const { someValue } = this.state;
this.setState({ loading: true });
try {
const { data, error } = await updateMutation({ variables: { value: someValue, key: 'foo' });
if (error) {
throw new Error(`Got an error: ${error}`);
}
} catch (err) {
console.log(err); // could handle the error here
}
this.setState({ loading: false });
}
render() {
const { data } = this.props;
const { someValue, loading } = this.state;
if (data.loading || loading) {
return <CircularProgress />;
}
return (
<form onSubmit={this.onSubmit}>
<TextField onChange={this.changeInput('someValue')} value={someValue} />
<Button type="submit">Submit</Button>
</form>
)
}
}
export default compose(
graphql(entryQuery, { variables: () => ({
// note that the above argument is props, so you can, for instance, use router params here
key: 'foo', // will always look up foo
})
}),
graphql(entryMutation, {
// mutate by default
name: 'updateEntry',
}),
)(SimpleFormWithGraphql)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment