solid func for beforeunload

I have some user data which I want to save before tab is closed. Using onCleanup() doesn't save the data. I had to write this, but wondering if solid provides something similar
const handleUnload = (_: BeforeUnloadEvent) => {
saveData();
};
onMount(() => {
window.addEventListener("beforeunload", handleUnload);
onCleanup(() => {
saveData();
window.removeEventListener("beforeunload", handleUnload);
});
});
const handleUnload = (_: BeforeUnloadEvent) => {
saveData();
};
onMount(() => {
window.addEventListener("beforeunload", handleUnload);
onCleanup(() => {
saveData();
window.removeEventListener("beforeunload", handleUnload);
});
});
2 Replies
Alex Lohr
Alex Lohr3mo ago
We do have a community primitive to save a bit of work: https://primitives.solidjs.community/package/event-listener#createeventlistener
Solid Primitives
A library of high-quality primitives that extend SolidJS reactivity
ATA noob
ATA noobOP3mo ago
export const Component = () => {
createEventListener(window, "beforeunload", () => saveData());
onCleanup(() => saveData());
return <></>
}
export const Component = () => {
createEventListener(window, "beforeunload", () => saveData());
onCleanup(() => saveData());
return <></>
}
Is this the recommended way? or should I just put the beforeunload listener directly on window
Want results from more Discord servers?
Add your server