supastarter for SvelteKitsupastarter for SvelteKitAPI
Mutate data with API
The previous example shows how to create a query, which means "getting data" from the API. If you want to perform a mutation (e.g. create, update, delete), you create a mutation endpoint instead.
This looks very similar to the query:
import { z } from "zod";
import { publicProcedure } from "../../trpc";
import { db, PostSchema } from "database";
export const createPost = publicProcedure
.input(
z.object({
title: z.string(),
content: z.string(),
}),
)
.output(PostSchema)
.mutation(async ({ input }) => {
const post = await db.post.create({
data: input,
});
return post;
});As with the query procedure, export the mutation procedure from your feature module's index.ts:
// ...
export * from "./create-post.ts";Use the mutation
To use the mutation you can use the apiClient again:
<script lang="ts">
import { page } from "$app/stores";
import { apiClient } from "@shared/lib/ApiClient";
let title = "";
let content = "";
async function onSubmit() {
await apiClient($page).post.createPost.mutate({ title, content });
}
</script>
<form on:submit|preventDefault={onSubmit}>
<input required placeholder="Title" bind:value={title} />
<textarea bind:value={content} />
<button type="submit" class="ml-4">Create Post</button>
</form>