kit icon indicating copy to clipboard operation
kit copied to clipboard

Feat: `onLeave` hook for load functions

Open kran6a opened this issue 5 months ago • 0 comments

Describe the problem

I have the need to use WS and SSE subscriptions on different pages across my site.

Currently, my known best way to do it is by initializing the subscription on .svelte files and using either an $effect or onMount to setup the cleanup funcion.

There was some discussion here about whether initializing subscriptions in +layout.ts files would provide any benefit over doing it on .svelte files and I found these:

https://github.com/sveltejs/svelte/discussions/12318#discussioncomment-10774342

Of course, this only applies to adapters that only run the load functions on client side (such as adapter-static, which is the one I use).

Describe the proposed solution

Adding an onLeave hook to load functions that allows passing a callback that is executed when navigating out of the page or layout.

export function load({ onLeave }) {
  const notifications = subscribe("/notifications");
  onLeave (()=>notifications.cancel());
  return {notifications};
}

This would start the subscription when the page is preloaded, make the notifications subscription available to all child layouts and pages, cancel the current subscription and resubscribe via invalidateAll/invalidate, all without having to put data fetching and manipulation logic in .svelte files, which I consider should only hold UI logic, specially when using adapter-static configured for true SPAs, where load functions are free from restrictions arising from data having to cross the server->browser gap.

The proposed function signature could be one of the following

type OnLeave = (from: URL, to: URL)=>Promise<void>;
type OnLeave = (from: URL)=>Promise<void>;
type OnLeave = ()=>Promise<void>;

If multiple +layout.ts/+page.ts files define an onLeave callback, they should be executed serially in reverse order (starting from the innermost +layout.ts/+page.ts) to prevent child layout callbacks from accessing objects that have been already disposed of on parent onLeave callbacks.

Alternatives considered

No response

Importance

would make my life easier

Additional Information

No response

kran6a avatar Sep 27 '24 14:09 kran6a