Skip to content

Commit

Permalink
[docs] Update useMutation demo
Browse files Browse the repository at this point in the history
  • Loading branch information
x0k committed Nov 4, 2024
1 parent 061f408 commit 55b5e0e
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 17 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
import { ShadowHost } from "@/components/shadow";
import Form from "./_generic-backend.svelte";
---

<ShadowHost client:only="svelte">
<Form client:only="svelte" />
</ShadowHost>
50 changes: 35 additions & 15 deletions apps/docs/src/content/docs/integrations/_generic-backend.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -4,48 +4,68 @@
import { useCustomForm } from "@/components/custom-form";
let isError = $state(false);
let duration = $state(0);
let data = $state<string>();
interface Config {
reject: boolean;
delay: number;
value: string;
}
const mutation = useMutation({
mutate: (_signal, value: string | undefined = "") =>
mutate: (_signal, { reject: isError, delay, value }: Config) =>
new Promise<string>((resolve, reject) => {
data = undefined;
isError = Math.random() > 0.5;
duration = Math.random() * 5000;
setTimeout(() => {
if (isError) {
reject(value);
} else {
resolve(value);
}
}, duration);
}, delay);
}),
onSuccess(response) {
data = response;
form.reset();
},
onFailure: console.error,
delayedMs: 1000,
timeoutMs: 3000,
delayedMs: 500,
timeoutMs: 2000,
});
const form = useCustomForm({
schema: {
type: "string",
properties: {
delay: {
type: "integer",
enum: [250, 1500, 2500],
default: 1500,
},
reject: {
type: "boolean",
},
value: {
type: "string",
},
},
},
uiSchema: {
delay: {
"ui:widget": "radio",
"ui:options": {
enumNames: ["250ms", "1.5s", "2.5s"],
},
},
},
onSubmit(config: Config | undefined) {
if (!config) return;
mutation.run(config);
},
onSubmit: mutation.run,
get disabled() {
return mutation.isProcessed;
},
});
</script>

<p>
Reject: {isError}, delay: {(duration / 1000).toFixed(2)}sec
</p>

<form use:form.enhance style="display: flex; flex-direction: column; gap: 1rem">
<FormContent bind:value={form.formValue} />
{#if mutation.isDelayed}
Expand Down
4 changes: 2 additions & 2 deletions apps/docs/src/content/docs/integrations/generic-backend.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@ sidebar:

import { Card, Code } from '@astrojs/starlight/components'

import Form from './_generic-backend.svelte';
import Form from './_generic-backend.astro';
import formCode from './_generic-backend.svelte?raw';

You can improve the experience of sending data to the server by using the `useMutation` hook.

<Code code={formCode} lang="svelte" />

<Card>
<Form client:only="svelte" />
<Form />
</Card>

0 comments on commit 55b5e0e

Please sign in to comment.