#Avoid "useSearchParams" in client components

4 messages · Page 1 of 1 (latest)

green pine
#

Hello everyone!
Im trying to pass searchParams from page props to client component and wrap them inside URLSearchParams object (to have possibility to add / remove and parse to url string).
My goal is to avoid using Suspense and UseSearchParams (I want to have full page with disabled javascript).
But Im facing an issue with typescript.
Full code example is available here:
https://codesandbox.io/p/sandbox/recursing-wright-zzr26y

Do you have any idea how to solve TS error under app/ClientComponent.tsx (in example above, line 10):

candid vortexBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

uneven lake
# green pine Hello everyone! Im trying to pass searchParams from page props to client compone...

the cause is that, if you want to initialise a URLSearchParams instance from a plain object, that object signature must be Record<string, string>. Next.js' searchParams prop type is slightly different with Record<string, string | string[] | undefined> so you need to convert it

const searchParams: Record<string, string | string[] | undefined> = {};

function removeUndefinedAndArray(
  obj: Record<string, string | string[] | undefined>
): Record<string, string> {
  return Object.entries(obj).reduce((acc, [key, value]) => {
    if (value === undefined) return acc;
    if (Array.isArray(value)) return { ...acc, [key]: value.at(0) }; // ?a=1&a=2&a=3 => { a: '1' }
    return { ...acc, [key]: value };
  }, {});
}

const urlSearchParams = new URLSearchParams(
  removeUndefinedAndArray(searchParams)
);
green pine
#

works like a charm !
Thanks!!