Skip to content

useSearchParams setter discards first update when called twice #547

@yinonburgansky

Description

@yinonburgansky

Describe the bug

When calling the setParams function from useSearchParams() twice in succession (synchronously), only the second call takes effect.
Additionally, the params proxy doesn't reflect the changes immediately after calling setParams.

Your Example Website or App

https://stackblitz.com/edit/github-g4uj2mjx-jikitf3w?file=src%2Froutes%2Findex.tsx

Steps to Reproduce the Bug or Issue

  1. click increment a and b
  2. only b has incremented and a has not.

Expected behavior

Both a and b parameters should be incremented.

Screenshots or Videos

No response

Platform

  • OS: Linux
  • Browser: Chrome
  • Version: 0.15.4

Additional context

This has come up when trying to create a helper hook to set search params:

function createSearchParamSignal<T>(
  key: string,
  transform: (val: string | string[] | undefined) => T
) {
  const [params, setParams] = useSearchParams();
  const getter = () => transform(params[key]);
  const setter = (val: T) =>
    setParams({ key: String(val) }, { replace: true, scroll: false });
  return [getter, setter] as const;
}

It would be nice to have the search param behave like signals:

const [a, setA] = createSearchParamSignal("a", (v) => (Number(v) || 0));
const [b, setB] = createSearchParamSignal("b", (v) => (Number(v) || 0));

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions