Next.js Discord

Discord Forum

Is there an easy way to set searchParams?

Answered
overyou posted this in #help-forum
Open in Discord
Hi, new to next js
I'm thinking of how I could make it so some of my components used URL as a source of state in next js 13. I kind of get it how i would make it for a components where you choose some single option (still, feels hacky), but what about a multiple choice element or smth similar? I have trouble understanding how i would implement something like that without weird workarounds.
It would be nice if i could do like:
"use client"
// https://localhost:3000/cars?company=42&company=99
const **handleChange **= (paramname, id) => {
  if (params.hasOwnProperty(paramname)) {
    setParams({...params, paramname: [...params.paramname, id]})
  }
  // ⋆⭒˚。⋆ imagine logic for other cases and for deletion ⋆⭒˚。⋆
}

<Multiple>
  <Option onClick={() => handleChange("company", "Toyota")} />
</Multiple>

I need to change the path so my fetch could just get it and send in to an API (not mine) as a query with searchParams. If there are better ways to do this with default fetch in server component, i would love to know.
Feels like I don't know something or that router's functionality isn't enough 😢. Isrouter.push the only way I can set URL? Any tips/guides are veeeery welcomed.
And also sorry for my English :fine:
Answered by @ts-ignore
you can create an array and then url encode that array
View full answer

10 Replies

Answer
@@ts-ignore you can create an array and then url encode that array
Can you, please, elaborate? I tried googling this and i don't really know if I searched for what you meant :pikachu_shocked:
you can do
router.push(`/search?q={encodeURI(multipleSelectValues)}`)
and then in that page
const params = useSearchParams()
const query = params.get("q")
const parsedQuery = query.contains(",") ? query.split(",") : query
this is just an example
@@ts-ignore Click to see attachment
Didn't know it can be done like this lol
If i wont be able to find some other solution built in next (apparently, there are none), this will help a lot, thanks! :meow_melt: