Working with Mutations
Mutations are used to modify data on your GraphQL server. This guide will show you how to create and execute mutations using Hyper Fetch.
What you'll learn
- How to create a GraphQL mutation.
- How to pass variables to a mutation.
- How to handle mutation responses.
Basic Mutation
Here is a basic example of how to create a mutation to log in a user.
import { Client } from "@hyper-fetch/core";
import { graphqlAdapter } from "@hyper-fetch/graphql";
import gql from "graphql-tag";
// 1. Initialize the client
const client = new Client({ url: "http://localhost:3000/graphql" }).setAdapter(graphqlAdapter);
// 2. Define types for the variables
type Variables = {
username: string;
password: string;
};
// 3. Create the mutation request
const login = client.createRequest<boolean, Variables>()({
endpoint: gql`
mutation Login($username: String!, $password: String!) {
login(username: $username, password: $password)
}
`,
});
// 4. Send the mutation with variables
const { data, error } = await login.send({
data: {
variables: {
username: "Some username",
password: "Some password",
},
},
});
Similar to queries, you can also use the .setData() method to provide variables for your mutation.
const { data, error } = await login
.setData({
username: "Some username",
password: "Some password",
})
.send();