Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: add Superforms example for Svelte 5 #42

Merged
merged 5 commits into from
Jan 20, 2025
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 53 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ async function validateToken(token: string, secret: string) {
}
```

## SvelteKit Example
## SvelteKit Example (Svelte 5)

In SvelteKit we can use form actions to easily setup a form with a captcha:

Expand Down Expand Up @@ -150,6 +150,58 @@ export const actions = {
};
```

## Superforms Example (Svelte 5)

`schema.ts`

```ts
import { z } from "zod";

export const schema = z.object({
..., // other fields
"cf-turnstile-response": z.string().nonempty()
});
```

`routes/login/+page.svelte`

```svelte
<script lang="ts">
// other imports
import { superForm } from 'sveltekit-superforms';
import { zodClient } from 'sveltekit-superforms/adapters';
import { schema } from './schema.ts';
import { Turnstile } from 'svelte-turnstile';

let { data }: { data: PageData } = $props();

const form = superForm(data.form, {
validators: zodClient(schema),
onUpdated() {
reset?.();
},
});

const { form: formData, enhance, message } = form;

let reset = $state<() => void>(); // reset the turnstile widget when the form is updated
</script>

<form method="POST" action="/login" use:enhance>
<Turnstile
on:callback={(event) => {
$formData['cf-turnstile-response'] = event.detail.token;
}}
ghostdevv marked this conversation as resolved.
Show resolved Hide resolved
on:expired={() => {
reset?.();
}}
ghostdevv marked this conversation as resolved.
Show resolved Hide resolved
siteKey={PUBLIC_TURNSTILE_SITE_KEY}
bind:reset />
</form>
```

This example uses the [Superforms onUpdated event](https://superforms.rocks/concepts/events) to reset the Turnstile widget. Additionally, it automatically adds the Turnstile response token to the form data.

# Resetting

If you need to manually reset the widget, you can do so by binding to the `reset` prop. For example:
Expand Down