sapper
sapper copied to clipboard
Best way for patching goto()? Unsaved data // onbeforeunload logic
Hey Sapper Community ❤️ I do:
async function gotoURL(...args) {
if (isFormUnsaved === true){
if (window.confirm("Are we leaving already?") === false){
return false;
}
}
return await goto(...args);
}
And it works for on:click.
How can I "patch" goto, for real links <a href="/somewhere">Meow</a>
I did what I want with "use" svelte functionality, but I think patching is a simpler solution.
I think something that you can use like this would be good:
<script>
import { onMount } from 'svelte';
import { onNavigate } from '@sapper/app';
onMount(() => onNavigate(() => !isFormUnsaved || window.confirm('Are we leaving already?')));
</script>
longer example
<script>
import { onMount } from 'svelte';
import { onNavigate } from '@sapper/app';
onMount(() => {
// `onNavigate` returns a function which "unsubscribes" the listener
const unlisten = onNavigate(page => {
// `page` (type `Page` from types.ts) is where the user navigates to
if (something_something) {
// returning `false` to prevent navigation
return false;
// or
return Promise.resolve(false);
}
});
// unsubscribe onDestroy
return () => unlisten();
});
</script>
Sooo, the way to prevent navigation in Sapper is to use this fork? I hope that case this is considered in Svelte Kit. Seems odd that a router can not prevent navigation!
As of now, svelte/kit does not have a solution for this. For anyone who needs this for the current sapper version, you can use my sapper-navigation-enhancer package. Im planning to make a similar package for svelte/kit, which should be a lot simpler.