sapper icon indicating copy to clipboard operation
sapper copied to clipboard

Best way for patching goto()? Unsaved data // onbeforeunload logic

Open SARFEX opened this issue 5 years ago • 4 comments
trafficstars

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>

SARFEX avatar Dec 31 '19 20:12 SARFEX

I did what I want with "use" svelte functionality, but I think patching is a simpler solution.

SARFEX avatar Dec 31 '19 20:12 SARFEX

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>

PatrickG avatar Jan 01 '20 23:01 PatrickG

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!

normano avatar Nov 05 '20 10:11 normano

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.

PatrickG avatar Mar 25 '21 12:03 PatrickG