With a working UI for querying sample data you added, you now need a UI to add new posts using GraphQL Mutations in Apollo React.
addPost
mutation, and a GraphQL mutation can return data, just like a query.
In this case, it makes sense to have the addPost
mutation return the same data
as the allPosts
query, because the UI should adjust to insert the new post
into the home page’s post list. GraphQL has a nice mechanism called fragments
to allow this type of reuse.
In the previous section, you added the allPosts
query like this:
allPosts
in the src/components/operations.graphql
file as
follows:
...postData
says “take the postData
fragment and use it here”.
src/components/operations.graphql
to add the
mutation that lets users add a post:
AddPostInput
input type.
TypeScript, and GraphQL Code Generator will make sure you provide an input of
the correct type. This mutation returns data of the same shape as the allPosts
query; you’ll see why that’s important when using the Apollo cache.
Run the following command to tell the GraphQL Code Generator to generate a React
hook, useAddPostMutation
, that extracts the component logic of this mutation
into a reusable function:
addPost({ variables: ... })
executes the mutation
with the passed-in post data, and after the GraphQL mutation returns, the
callback functions are executed.
allPosts
query, as follows:
allPosts
query to execute (a second
round trip)allPosts
query is re-executed, it changes the data
value of
const { data, loading, error } = useAllPostsQuery()
in the post list
component, and React re-renders that component.
Again, this works, but it could be more efficient: The UI actually already has
all of the data it needs to render the updated UI after the first round trip,
because the new post on the server is only going to be the post that was added
by the mutation. So, to avoid a trip to the server, you can manually update
Apollo’s view of the result of the allPosts
query and force the re-render,
without round-tripping to the server. That’s done by editing the cached value,
as follows:
addPost
function to run the addPost
mutation, and on
completion inserts the new post into the cache.
src/component/header.tsx
. This logic adds a button that shows a modal to add
the post. The visibility of the modal is controlled by React state, set up
through the useState
hook, as follows:
addPost
function, as follows:
src/component/header.tsx
file looks as follows:
yarn start
command, and then navigate to
http://localhost:3000
to see the post list on the home screen. Then, you can
click Create Post to add a new post to the backend GraphQL database. After
submitting the post, you’ll see it in the post list.
The user the post is added for is hard-coded in this step (to “TestUser”).
We’re just about there. Let’s wrap up what we’ve learned.