Adding new comments with a GraphQL mutation
This lesson will show how to extend the hook to handle adding new comment logic. It will cover adding a new GraphQL mutation and using it from the frontend application.
In this lesson, we will cover adding new comments — we'll write a GraphQL mutation for inserting a new entry to the database, and we'll call it from the frontend application.
Firstly, let's go to the Hasura Console to create and test a GraphQL mutation.
In the GraphiQL explorer, we can see
insert_comments allows us to add multiple comments, but we'll only
add one at a time, so let's go with
In the mutation, we're going to pass
arguments. Try it out in GraphiQL if you want!
We'll store it as a constant in our code and then implement the
function inside our hook. It's going to be pretty similar to our
function. We also need to send a POST request and handle the response.
Let's start with the function signature. Our GraphQL mutation takes three
content. We already know the topic inside of
the hook, as it was provided as the hook's parameter. Our function just needs to
take the remaining two pieces of information. What's the type of the parameters?
Instead of writing a new one, we can use the
Pick utility type to "pick"
comment properties from the
Pick<Type, Keys> — Constructs a type by picking the set of properties Keys (string literal or union of string literals) from Type.
Now that we have the function, we can add the Hasura API call. We'll again use a
fetch function, whose arguments will look very similar to fetching the
comments. We'll provide an URL to our Hasura instance and specify the config:
The same headers as before —
In the request's body, we'll provide just created GraphQL mutation and variables —