onNavigate lifecycle function
See original GitHub issue#552 suggested a need for a lifecycle function that gets called when navigation occurs but the destination component is the same as the one we’re already on (since onMount
only runs the first time the component is mounted, and the alternative — unmounting components upon navigation — is bad for a variety of reasons).
I propose an onNavigate
hook that lives in $app/navigation
and looks something like this:
export function onNavigate(fn) {
let mounted = false;
const unsubscribe = getStores().page.subscribe(() => {
if (mounted) fn();
});
onMount(() => {
mounted = true;
fn();
return () => {
unsubscribe();
mounted = false;
}
});
}
<script>
import { onMount } from 'svelte';
import { onNavigate } from '$app/navigation';
onMount(() => {
// runs once when the page mounts
});
onNavigate(() => {
// runs when the page mounts, and also whenever SvelteKit
// navigates to a new URL but stays on this component
});
</script>
As mentioned in https://github.com/sveltejs/kit/issues/404#issuecomment-800630109:
There might be some nuance around ensuring that the callback doesn’t run immediately before the component is unmounted, but you get the gist. This would work in any component (layout or otherwise) like a normal lifecycle function, including components created after the page was initially created (e.g. lazily-loaded stuff).
Issue Analytics
- State:
- Created 3 years ago
- Reactions:13
- Comments:9 (5 by maintainers)
Top GitHub Comments
We need a hook onBeforeNavigate as well. As referenced by @benmccann in sapper#1047, it’s very useful to be able to cancel navigation when a user is editing something and has forgotten to click “Save”. For example, I show a dialog “You didn’t save your changes. Do you want to stay on the page or lose your changes?”. A basic onNavigate hook doesn’t allow this kind of behavior.
If this will not be handled by svelte/kit, I will provide a package for it, simliar to this. But I think it would be good, if this were handled by svelte/kit. I would call it
beforeNavigate
analogous tobeforeUpdate
.One question is, should
onbeforeunload
handled by it, too?