ciscoheat / sveltekit-flash-message

Send temporary data after redirect, usually from endpoints. Works with both SSR and client.
https://www.npmjs.com/package/sveltekit-flash-message
MIT License
246 stars 5 forks source link

Timeout and clear message #6

Closed mike-lloyd03 closed 1 year ago

mike-lloyd03 commented 1 year ago

Hey thanks for this library. It's working great. Is there a recommended way to handle automatically clearing a message after a certain amount of time?

ciscoheat commented 1 year ago

Hey, glad you like it! :) I'd handle that with a reactive statement just below the flash initialization, like this:

import { initFlash } from 'sveltekit-flash-message/client';
import { page } from '$app/stores';

const flash = initFlash(page);

const timeoutMs = 5000;
let flashTimeout: ReturnType<typeof setTimeout>;

$: if ($flash) {
  clearTimeout(flashTimeout);
  flashTimeout = setTimeout(() => ($flash = undefined), timeoutMs);
}

I will add that to the readme!

mike-lloyd03 commented 1 year ago

Works perfectly! Thank you!

mike-lloyd03 commented 1 year ago

One other question. When sending the flash message, I'm following the Readme example:

    const message = { type: 'success', message: "Logged in" };
    throw redirect(message, event);

But doing this raises the following warning:

Argument of type '{ type: string; message: string; }' is not assignable to parameter of type '{ type: "success" | "error"; message: string; }'.
Types of property 'type' are incompatible.
Type 'string' is not assignable to type '"success" | "error"'.

My solution is this:

    const type: "success" = "success";
    const message = { type, message: "Logged in" };
    throw redirect(message, event);

I'm new to Typescript but is this the idiomatic way to do this?

ciscoheat commented 1 year ago

Yes, the problem is that when you create message as a separate variable, typescript widens the type of string literals to string, so it doesn't match the literal type of redirect.message.

Two solutions:

// Add 'as const' to make the type literal
const message = { type: 'success', message: "Logged in" } as const;
throw redirect(message, event);

// Or pass it directly as a parameter, so it won't be widened by the compiler
throw redirect({ type: 'success', message: "Logged in" }, event);

Read more about type widening/narrowing here: https://dev.to/toluagboola/type-widening-and-narrowing-in-typescript-5ejo

Readme updated with this, thanks for the notice!