Skip to main content

GraphQL mutations

A todo list on the public GraphQLZero API. Adding, checking and deleting a todo each send a GraphQL mutation, and the result of the mutation is written into the cached todos query. The list updates without a second request, and a log shows every cache write.

intermediategraphqluseSubmitsendcache
import { useFetch, useSubmit } from "@hyper-fetch/react";
import { type FormEvent, useState } from "react";

import { createTodo, deleteTodo, type Todo, todosQuery, updateCachedTodos, updateTodo } from "./api";

export const App = () => {
const [title, setTitle] = useState("");
const [log, setLog] = useState<string[]>([]);
const addLog = (line: string) => setLog((current) => [line, ...current].slice(0, 5));

const { data, error, loading } = useFetch(todosQuery);
const create = useSubmit(createTodo);

create.onSubmitSuccess(({ response }) => {
// GraphQLZero gives every new todo the id 201. A real API returns a unique one, use it as it is.
const todo = { ...response.data.createTodo, id: `new-${Date.now()}` };
updateCachedTodos((todos) => [todo, ...todos]);
addLog(`createTodo -> added "${todo.title}" to the cache`);
setTitle("");
});

const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
create.submit({ payload: { input: { title, completed: false } } });
};

const toggle = async (todo: Todo) => {
const response = await updateTodo.send({
payload: { id: todo.id, input: { completed: !todo.completed } },
});
if (!response.data) return addLog(`updateTodo failed: ${response.error?.[0]?.message ?? "network error"}`);
// Take the new value from the mutation result, the way you would with any GraphQL server.
const { completed } = response.data.updateTodo;
updateCachedTodos((todos) => todos.map((item) => (item.id === todo.id ? { ...item, completed } : item)));
addLog(`updateTodo -> todo ${todo.id} is ${completed ? "done" : "open"} in the cache`);
};

const remove = async (todo: Todo) => {
const response = await deleteTodo.send({ payload: { id: todo.id } });
if (!response.data?.deleteTodo) return addLog("deleteTodo failed");
updateCachedTodos((todos) => todos.filter((item) => item.id !== todo.id));
addLog(`deleteTodo -> removed todo ${todo.id} from the cache`);
};

return (
<main className="container">
<hgroup>
<h1>GraphQL mutations</h1>
<p>Each mutation writes its result into the cached query, so the list updates without fetching it again.</p>
</hgroup>
<form onSubmit={handleSubmit}>
<fieldset role="group">
<input value={title} onChange={(event) => setTitle(event.target.value)} placeholder="New todo" required />
<button type="submit" aria-busy={create.submitting} disabled={create.submitting}>
Add
</button>
</fieldset>
{create.error && <small className="error">{create.error[0]?.message ?? "Could not add the todo"}</small>}
</form>
<div className="grid-2">
<article>
{loading && !data && <p aria-busy="true">Loading todos...</p>}
{error && <p className="error">Could not load todos: {error[0]?.message ?? "network error"}</p>}
<ul className="list">
{data?.todos.data.map((todo) => (
<li key={todo.id}>
<label>
<input type="checkbox" checked={todo.completed} onChange={() => toggle(todo)} />
{todo.title}
</label>
<button type="button" className="outline secondary" onClick={() => remove(todo)}>
Delete
</button>
</li>
))}
</ul>
</article>
<article>
<header>Cache log</header>
{log.length === 0 && <p className="muted">Add, toggle or delete a todo.</p>}
<ul className="log">
{log.map((line, index) => (
<li key={`${index}-${line}`}>{line}</li>
))}
</ul>
</article>
</div>
</main>
);
};
Run locallynpx tiged BetterTyped/hyper-fetch/examples/react/graphql-mutations hyper-fetch-react-graphql-mutations && cd hyper-fetch-react-graphql-mutations && npm install && npm run dev
What it shows
  1. Mutations are requests: the operation goes in document, the variables in the payload, and the response is typed with the usual generics.
  2. useSubmit for the create form, request.send() for actions on a single row.
  3. client.cache.update() writes mutation results into the cached query, and every useFetch that reads it re-renders.
  4. Variables in the cache key: the list query is created once with its variables, so the hook and the cache updates point at the same entry.

How it works​

  1. api.ts sets GraphqlAdapter() on the client. Every request has endpoint: "/api", the URL path of the GraphQL server, and the operation in document. The mutations declare their variables in payload, for example { id: string; input: { completed: boolean } } for updateTodo.

  2. todosQuery is getTodos.setPayload({ options: { paginate: { page: 1, limit: 6 } } }). The variables are a part of the cache key, so useFetch(todosQuery) and updateCachedTodos() must use this exact request.

  3. updateCachedTodos(change) calls client.cache.update(todosQuery, ...) with a function that gets the cached response and returns the new data:

    client.cache.update(todosQuery, (cached) =>
    cached?.data ? { data: { todos: { data: change(cached.data.todos.data) } } } : {},
    );
  4. App adds a todo with useSubmit(createTodo). In onSubmitSuccess it puts response.data.createTodo at the top of the cached list.

  5. Checking a todo calls updateTodo.send({ payload }) and merges the completed value the server returned. Deleting calls deleteTodo.send() and removes the row when the server answers true. A failed mutation leaves the cache alone and logs the first GraphQL error.

GraphQLZero answers mutations like a real server but does not store them, so a refetch would bring back the original list. That is also why the app gives each new todo a local id: the API returns 201 for all of them.

When to use it
  • The mutation returns the changed object, so you already have the data the list needs.
  • Lists where a full refetch is slow or expensive, such as long or paginated queries.
  • When a mutation affects many queries, invalidate them instead with client.cache.invalidate().

Summary

GraphQL mutations are regular HyperFetch requests with the operation in document and variables in the payload. Write their results into the cached query with client.cache.update() and every component showing it updates at once.