Skip to content

A declarative way to redirect #137

@krishnagopinath

Description

@krishnagopinath

Thank you for this fantastic library!

I believe that a "declarative" way to redirect to a desired route would be very useful. Something like this: https://reacttraining.com/react-router/web/api/Redirect

Its probably very easy to implement this in user land with the navigate function, but it would great if the library provided a way to do that, so there aren't hundreds of implementations out there!

Here's how usage would look like:

{#await auth.verify()}
    <Spinner />
{:then}
    {#if adminOnly && $user.role !== 'admin'}
		    <Redirect path="/" />	
    {:else}
        <slot />
    {/if}
{:catch}
    <Redirect path="/login" replace />
{/await}

That's definitely more "declarative" than what I do now:

<script>
import { navigate } from 'svelte-routing'

export let adminOnly = false;

function verifyUser() {
	return auth.verify().then(user => {
		if (adminOnly && $user.role !== 'admin') {
			return navigate('/')
			throw new Error('error so that `#await` block `then` is not run')	
		}
	}).catch(err => {
		navigate('/login')
		
		// Rethrow error so that the `#await` block works correctly
		throw err
	})
}

</script>
{#await verifyUser()}
    <Spinner />
{:then}
    <slot />
{/await}

This is definitely more boilerplate-y than the proposed version.

I'd love to know your thoughts about this!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions