-1

i am preparing a query params for an array, but now i would like to have with this format

?vegetable[]=tomato&foo[]=lechuce

this is my current code:

import { useSearchParams } from 'react-router-dom'

const [searchParams, setSearchParams] = useSearchParams()
searchParams.set('vegetable', ['tomato', 'lechuce']) 

with that i am getting

?vegetable=tomato%2Clechuce

but i need

?vegetable[]=tomato&foo[]=lechuce

and my other small question is:

how can i add '?' to start to search

i am doing like this:

navigate(location?.pathname + '?' + searchParams.toString())

its necesary use navigate?

11
  • what does your title have to do with this? Commented Oct 11, 2023 at 14:16
  • @DanielA.White sorry i keept my previous question, and i forgot change the title Commented Oct 11, 2023 at 14:18
  • I'm guessing react-router doesn't support that - you might want to consult their documentation Commented Oct 11, 2023 at 14:19
  • useSearchParams returns a URLSearchParams object Commented Oct 11, 2023 at 14:25
  • @Konrad that is using URLSearchParams and i am using react-route Commented Oct 11, 2023 at 14:26

1 Answer 1

2

In my opinion. How about to use set and append function like this.

import { useSearchParams } from 'react-router-dom';

const [searchParams, setSearchParams] = useSearchParams();

searchParams.set('vegetable', 'vege1');
searchParams.set('foo', 'foo1');

searchParams.append('vegetable', 'vege2');
searchParams.append('foo', 'foo2');

You can check this value :

console.log(earchParams.toString());

Let me know if you still have more issues.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.