This video is available to students only

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.

GraphQL mutation#

Firstly, let's go to the Hasura Console to create and test a GraphQL mutation.

In the GraphiQL explorer, we can see insert_comment_one and insert_comment mutations. insert_comments allows us to add multiple comments, but we'll only add one at a time, so let's go with insert_comments_one.

In the mutation, we're going to pass topic, author, and content as arguments. Try it out in GraphiQL if you want!

We'll store it as a constant in our code and then implement the addComment function inside our hook. It's going to be pretty similar to our fetchComments function. We also need to send a POST request and handle the response.

addComment function#

Let's start with the function signature. Our GraphQL mutation takes three arguments: topic, author, and 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"content and comment properties from the Comment type.

TypeScript docs:

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 native 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:

  • POST request method.

  • The same headers as before — x-hasura-role and Content-Type.

  • In the request's body, we'll provide just created GraphQL mutation and variables — topic, content, author.

Start a new discussion. All notification go to the author.