Apollo Mutations

I have been continuing on my journey of learning how to implement the Apollo client into a React app. Previously I discussed the setup and making queries and today I am going to tackle mutations. If you’re not familiar with GraphQL, mutations are calls to the database that create something new or make an update to an existing record. I am going to focus on creating a new user in this blog. Let’s begin!
First we need to import gql and our useMutation hook from the Apollo client, so we write this at the top of our file:
import { gql, useMutation } from '@apollo/client'
Then we write the mutation we want by wrapping it in a gql string. In this case I am creating a new user by using the AddUser mutation I set up on the backend and passing it an email and username to create the user.
const ADD_USER = gql`
mutation AddUser($email: String!, $username: String!){
addUser(email: $email, username: $username) {
user {
id
username
email
}
}
}
`
The mutation call doesn’t get called immediately. Instead it is assigned to a function that we can call to invoke the mutation. In this case, I set mine up where addUser was the function that uses the mutation hook which gets passed the gql string I created.
const [addUser, { data }] = useMutation(ADD_USER);
Next, I wrote a very simple form to allow the user to input their username and email. When this form is submitted I call the onSubmit function below which then calls the addUser function to make the mutation call to the database. So until the user hits the submit button, no mutation happens. When they hit submit it makes the mutation query and creates the user.
function onSubmit(e) {
e.preventDefault();
addUser({variables: {email: e.target[1].value, username: e.target[0].value}});
}
This is a very basic example of using Apollo to create a user in the database. I plan to continue playing around with this application to figure out some more difficult calls that would happen, but I was happy I got this far and now have a grasp on what is happening between Apollo and GraphQL!