Timeout and clear message
mike-lloyd03 opened this issue · 4 comments
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?
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!
Works perfectly! Thank you!
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?
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!