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

Created on 31 Dec 2019  路  3Comments  路  Source: sveltejs/sapper

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>

question routing

Most helpful comment

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>

All 3 comments

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!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

milosdjakovic picture milosdjakovic  路  3Comments

freedmand picture freedmand  路  4Comments

mylastore picture mylastore  路  3Comments

Snugug picture Snugug  路  4Comments

Rich-Harris picture Rich-Harris  路  4Comments