Redirect the user after a form submission
Asked Answered
H

1

5

I have an <input type="text" /> as a search bar inside a <form>.

Because it's a search bar the user should be redirected to a route similar to : /search?q=thingIWantToSearch when the form is submited.

Currently I'm doing with a location.href but I don't think this is a good way of doing it (or is it?)

Here's my code :

<script>
    let inputValue = '';

    const handleSubmit = () => {
        // there should be some parsing before putting it in the url, but it's not the subject
        location.href = `/search?q=${inputValue}`;
    }
</script>

<form on:submit|preventDefault={handleSubmit}>
    <input type="text" bind:value={inputValue} />
    <button type="submit">submit</button>
</form>

So how can I properly redirect the user on form submission?

Hilaria answered 23/10, 2019 at 16:25 Comment(4)
Look into the History API, specifically the replaceState() function.Carrasquillo
@BennyHinrichs is this "friendly" for sapper's router ?Hilaria
@BennyHinrichs sapper seems to give an id property to history.state that increment every time something is pushed to the history. That mean a replaceState() should manually increment the id to keep the history intact. The issue is if sapper change his way to manage the history, it could create some unexpected bugs and force me to update every redirections.Hilaria
Oh, I didn't see the Sapper tag!Carrasquillo
O
10

If you are using SvelteKit you can use the built-in goto function from $app/navigation. Previously Sappers goto function served the same purpose.

Here's how you can use it:

<script>
  import { goto } from '$app/navigation';

  let inputValue = '';

  const handleSubmit = () => {
    // there should be some parsing before putting it in the url, but it's not the subject
    goto(`/search?q=${inputValue}`);
  };
</script>

<form on:submit|preventDefault="{handleSubmit}">
  <input type="text" bind:value="{inputValue}" />
  <button type="submit">submit</button>
</form>
Outrelief answered 24/10, 2019 at 12:2 Comment(4)
This is what I needed. Thanks you !Hilaria
|preventDefault did the trick for me! Thanks a lot <3Aquamanile
this works in sveltekit as wellPolis
In SvelteKit use: import { goto } from '$app/navigation';Gay

© 2022 - 2024 — McMap. All rights reserved.