The Apollo Mutation component

The Mutation component is very similar to the Query component. Be sure to undo the HoC solution changes before continuing. Follow these steps to get the Mutation component running:

  1. Import the Mutation component from the react-apollo package, as follows:
import { Query, Mutation } from 'react-apollo';
  1. Export the Feed component again, as we did in the previous Query component example. Remove the ADD_POST_MUTATION and GET_POSTS_QUERY variables when doing so:
export default class Feed extends Component
  1. Next, add the Mutation component inside of the render function. We will surround the form with this component, as this is the only part of our content where we need to send a mutation:
render() {
const self = this;
const { postContent } = this.state;

return (
<Query query={GET_POSTS}>
{({ loading, error, data }) => {
if (loading) return <p>Loading...</p>;
if (error) return error.message;

const { posts } = data;

return (
<div className="container">
<div className="postForm">
<Mutation mutation={ADD_POST}>
{addPost => (
<form onSubmit={e => {
e.preventDefault();
addPost({ variables: { post: { text: postContent
} } }).then(() => {
self.setState((prevState) => ({
postContent: ''
}));
});
}}>
<textarea value={postContent} onChange=
{self.handlePostContentChange} placeholder="Write
your custom post!"/>
<input type="submit" value="Submit" />
</form>
)}
</Mutation>
</div>
<div className="feed">
{posts.map((post, i) =>
<div key={post.id} className="post">
<div className="header">
<img src={post.user.avatar} />
<h2>{post.user.username}</h2>
</div>
<p className="content">
{post.text}
</p>
</div>
)}
</div>
</div>
)
}}
</Query>
)
}

The surrounded form now directly implements the onSubmit function. We could also extract this to a separate class method, but it is working this way. The Mutation component accepts the mutation property, which receives the GraphQL request that we want to send. The form can access the addPost function, which is exposed inside of the render prop function.

The render function is now more complex than it was before. In my opinion, the HoC solution looks much cleaner, despite the advantages that this solution might have. In the next chapter, we will look at how to make this more readable and reusable. No matter which approach you choose, the result will be the same.

You can now try out the Mutation component by submitting a new post. Our feed does not show the post until we refresh the browser again. In the next section, we will look at how to fix this issue.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.134.102.182