-
I have a login page with a login form that triggers a form action. The form action returns the user information to the page which uses that user information to set the user store context. I want to redirect after this but I am finding this redirect and goto difficult to use. I find if i use "goto" i get an error saying "Cannot call goto(...) on the server" If i wrap "goto" in an if statement if it is browser then I get a flash of content before the redirect happens. If i put "redirect" in the form action then the store context does not get set on the page because we are redirecting before the page receives the context. If I add "goto" and "redirect" to the page as below then nothing happens: <script lang="ts">
import { browser } from "$app/environment";
import { goto } from "$app/navigation";
import user from "$lib/stores/user";
import { redirect } from "@sveltejs/kit";
import { setContext } from "svelte";
import LoginForm from "$lib/components/forms/loginForm.svelte";
export let form;
if (form?.user) {
user.set(form.user);
setContext('user', user);
if (browser) {
goto("/dashboard/events")
} else {
redirect(308, "/dashboard/events")
}
}
</script>
<main class="container flex flex-col items-center justify-end md:justify-center py-6 md:py-24">
<LoginForm />
</main> Whats the recommended approach here? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
This kind of logic should be placed inside load functions rather than pages. |
Beta Was this translation helpful? Give feedback.
-
This is because the code in the
Might be because the document is downloaded but
I think can use See an example here https://kit.svelte.dev/docs/form-actions#anatomy-of-an-action RecommendationUse AlternativeCustomise your form submission behaviour with |
Beta Was this translation helpful? Give feedback.
-
Thanks for your inputs. I did this and its working: <script lang="ts">
// imports removed for readability
export let form;
// wrapping 'form' in reactive code runs when changes happened in the form object on the server, after log in server action runs
$: {
if (form?.error) {
general.toastError('Invalid email or password. Please try again');
}
if (form?.user) {
// set store
user.set(form.user);
setContext('user', user);
// redirect
const redirectTo = $page.url.searchParams.get("redirectTo")
if (form.user.role.id === 4) {
goto(redirectTo || '/dashboard/events');
} else if (form.user.role.id === 1) {
goto(redirectTo || '/events');
}
}
}
</script>
<main>
<form
action="?/login"
method="POST"
use:enhance={() => {
loading = true;
return async ({ update }) => {
loading = false;
await update({ reset: false });
};
}}
>
...
</form>
</main>
|
Beta Was this translation helpful? Give feedback.
Thanks for your inputs. I did this and its working: