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.
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
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>
);
};
npx tiged BetterTyped/hyper-fetch/examples/react/graphql-mutations hyper-fetch-react-graphql-mutations && cd hyper-fetch-react-graphql-mutations && npm install && npm run dev- Mutations are requests: the operation goes in
document, the variables in the payload, and the response is typed with the usual generics. useSubmitfor the create form,request.send()for actions on a single row.client.cache.update()writes mutation results into the cached query, and everyuseFetchthat reads it re-renders.- 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
-
api.tssetsGraphqlAdapter()on the client. Every request hasendpoint: "/api", the URL path of the GraphQL server, and the operation indocument. The mutations declare their variables inpayload, for example{ id: string; input: { completed: boolean } }forupdateTodo. -
todosQueryisgetTodos.setPayload({ options: { paginate: { page: 1, limit: 6 } } }). The variables are a part of the cache key, souseFetch(todosQuery)andupdateCachedTodos()must use this exact request. -
updateCachedTodos(change)callsclient.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) } } } : {},); -
Appadds a todo withuseSubmit(createTodo). InonSubmitSuccessit putsresponse.data.createTodoat the top of the cached list. -
Checking a todo calls
updateTodo.send({ payload })and merges thecompletedvalue the server returned. Deleting callsdeleteTodo.send()and removes the row when the server answerstrue. 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.
- 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().
Related
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.
