Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dynamic Route Params from Form Submit

I have a form that is passing a string to a search page that uses that string to query an API and display results. When I submit the form, the URL is x/search/string?slug=string. I am looking for a way to keep the URL cleaner and have it be x/search/string.

My form code:

<script lang="ts">
    let slug = '';
</script>

<form action={`search/${slug}`}>
    <input bind:value={slug} name="slug" type="text" />
    <button type="submit" />
</form>

My +page.server.ts code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

export const load: PageServerLoad = async ({fetch, params}) =>{

  const fetchSearchResults = async (slug:string) => {
    const res = await fetch(`https://openlibrary.org/search.json?q=${slug}`)
    const data = await res.json();
    return {data};
  }
  return {
    results: fetchSearchResults(params.slug)
  }
}

The URL x/search/string?slug=string provides the same results as x/search/string but I am positive I am doing something wrong. Any help or links to some examples that would help would be greatly appreciated.

>Solution :

The input in the form is sent as part of the form request, for GET that results in query parameters.

There are multiple options, e.g. remove the name attribute.

You could also move the element out of the form, but I would not recommend that, as it breaks things like being able to press Enter to submit the form.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading