Skip to content

Uncouple useSearchParams from SvelteKit #378

@KieranP

Description

@KieranP

Describe the feature in detail (code, mocks, or screenshots encouraged)

Context: I have a Svelte application, not run on SvelteKit. Svelte files are compiled, user hits a Rails application, where the relevant pages svelte file is then loaded and mounted to a root div element. Works really well.

I see that useSearchParams has a requirement on SvelteKit. Do you think it would be possible to uncouple or make a version of useSearchParams that doesn't rely on SvelteKit?

It would be nice to be able to use useSearchParams and watch within our Svelte components. For e.g., when user goes to /admin/users, and we load the matching Svelte file, we currently need to parse location.search and pass into URLSearchParams, and then use $effect with a bunch of joining logic. e.g.

<script>
  let results = $state([])
  let searchParams = $state(new URLSearchParams(window.location.search))
  let query = $state(searchParams.get('query'))
  let page = $state(searchParams.get('page'))

  function buildParams(...args) {
    return { query, page }
  }

  function updateParams() {
    // params = buildParams() 
    // searchParams = (merge searchParams and params)
    // window.location.search = searchParams.toString()
  }

  $effect(() => {
    updateParams(query, page) // watches for changes

    let url = window.location.pathname
    url += '?' + searchParams.toString()
    fetch(url).then((response => {
      results = response.json()
    )
  })
</script>

Query: <input type="text" bind:value={query} />
Page: <input type="number" bind:value={page} />

{#each results as result (result.id)}
  ...
{/each}

It would be nicer to use useSearchParams and watch:

<script>
  import { useSearchParams, watch } from 'runed'
  import { usersQuerySchema } from 'schemas'

  let results = $state([])
  let params = useSearchParams(usersQuerySchema);

  watch(
    () => params.toURLSearchParams(),
    () => {
      let url = window.location.pathname
      url += '?' + params.toURLSearchParams().toString()
      fetch(url).then((response => {
        results = response.json()
      )
    }
  )
</script>

Query: <input type="text" bind:value={params.query} />
Page: <input type="number" bind:value={params.page} />

{#each results as result (result.id)}
  ...
{/each}

What type of pull request would this be?

Enhancement

Provide relevant links or additional information.

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    triagePending triage by a maintainer to give it proper labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions