Last active
May 18, 2018 23:49
-
-
Save malbernaz/c1f44926a00f632f2aad85afcce06f62 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
const ALL_POSTS = graphql` | |
query($orderBy: PostOrderBy) { | |
allPosts(orderBy: $orderBy) { | |
title | |
content | |
createdAt | |
updatedAt | |
} | |
} | |
`; | |
const CREATE_POST = graphql` | |
mutation($content: String, $title: String, $authorId: ID!) { | |
createPost(content: $content, title: $title, authorId: $authorId) { | |
title | |
content | |
createdAt | |
updatedAt | |
} | |
} | |
`; | |
const mutations = { | |
createPost: { | |
query: CREATE_POST, | |
update: ({ mutate, allPosts }, variables) => | |
mutate(variables).then(({ createPost: post }) => ({ | |
allPosts: [post, ...allPosts] | |
})), | |
optmisticUpdate: ({ allPosts }, variables) => ({ | |
allPosts: [variables, ...allPosts] | |
}) | |
} | |
}; | |
export class PostForm extends Component { | |
state = { title: "", content: "" }; | |
updateField = field => event => this.setState({ [field]: event.target.value }); | |
render() { | |
return ( | |
<GrafooConsumer | |
mutations={mutations} | |
query={ALL_POSTS} | |
variables={{ orderBy: "createdAt_DESC" }} | |
skipCache={false} | |
render={({ allPosts, loading, loaded, errors, createPost }) => ( | |
<Fragment> | |
<h1>New Post</h1> | |
<form | |
onSubmit={ | |
event => { | |
event.preventDefault(); | |
createPost(this.state) | |
} | |
} | |
> | |
<input | |
value={this.state.title} | |
onChange={this.updateField("title")} | |
/> | |
<textarea | |
value={this.state.content} | |
onChange={this.updateField("content")} | |
/> | |
<button>submit</button> | |
</form> | |
{loaded ? ( | |
allPosts.map(post => <Post key={post.id} post={post} />) | |
) : ( | |
<Spinner /> | |
)} | |
</Fragment> | |
)} | |
/> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment