Skip to content
Closed
Show file tree
Hide file tree
Changes from all 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
41 changes: 41 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,47 @@ $effect(() => {
});
```

`takeFlash` can be used to prevent the flash message store from being updated with the flash message. This can be useful for applying custom handling to the flash message in progressively enhanced forms:

```svelte
<script lang="ts">
import { toast } from "svelte-sonner";
import { takeFlash } from 'sveltekit-flash-message';
import { superForm } from "sveltekit-superforms";

let toastId: string | number | null = null;
const { form, enhance } = superForm(
{ test: "" },
{
onSubmit: () => {
toastId = toast.loading("Pending...");
},
onResult: async ({ result }) => {
if (toastId !== null) {
// Prevent the flash message store in `src/routes/+layout.svelte` from being updated.
// Instead, we manually take the flash message here and update the already pending toast.
const flash = await takeFlash();
if (!flash) return;
if (result.type === "error" || result.type === "failure") {
toast.error(flash.message, {
id: toastId,
action: { label: "Retry", onClick: () => { /* Retry logic here */ }, },
});
} else {
toast.success(flash.message, { id: toastId });
}
}
},
},
);
</script>

<form method="POST" action="/test" use:enhance>
<input type="text" name="test" bind:value={$form.test} />
<button>Submit</button>
</form>
```

## Flash message options

When calling `getFlash`, you can specify options, which will be inherited for the current route and the ones below.
Expand Down
16 changes: 16 additions & 0 deletions src/lib/client.svelte.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,22 @@ export async function updateFlash(page: Readable<Page> | Page, update?: () => Pr
return !!cookieData;
}

/**
* Take the flash message, preventing the flash message store from being updated with the message. Useful with progressively enhanced forms for applying custom handling to the flash message.
* @param page Page store, imported from `$app/stores`.
* @returns {Promise<App.PageData['flash']>} The flash message if it existed, `undefined` if not.
*/
export async function takeFlash(page: Readable<Page> | Page) {
const cookieData = parseFlashCookie() as App.PageData['flash'] | undefined;

if (cookieData !== undefined) {
if (browser) await tick();
const flash = getRouter(page).getFlashMessage(get(page).route.id);
clearFlashCookie(flash.options.flashCookieOptions);
return flash;
}
}

///////////////////////////////////////////////////////////

function clearFlashCookie(options: CookieSerializeOptions) {
Expand Down