'How to send MULTIPLE params with useHistory hook in React?

history.push({pathname: '/search?', state: {param1: 'value1'}}) this doesn't work. It just redirects to /search

history.push('/search?', {param1: 'value1'}) this doesn't work.

history.push('/search?', ['param1=value1']) this doesn't work.

history.push('/search?', [... 'param1=value1']) this doesn't work.

history.push('/search?', state: {param1: 'value1'}) this doesn't work.

The only thing that works is this: history.push('/search?param1=value1').

But I need to dynamically send multiple params. How do I do that? The official documentation shows the first example with an object, but it's not working for me. I am using functional components by the way.



Solution 1:[1]

If I understand your question correctly you want to dynamically get/set the queryString parameters of the URL.

None of the examples you've shared work because the second argument to history.push is route state.

history.push(path|To, [state])

Trying to pass queryString parameters in the second argument doesn't work.

Use URLSearchParams to construct a searchParams object that you can then update the params of, to be used in the history.push method. This method persists any existing queryString parameters.

Example:

const { search } = useLocation();

...

// get the search params for the current location
const searchParams = new URLSearchParams(search);

// update params as necessary, i.e. set/delete
searchParams.set("param1", "value1");
searchParams.set("param2", "value2");
searchParams.set("param3", "value3");

// push new route using to object
history.push({
  pathname: "/search",
  search: searchParams.toString(),
});

OFC, if you don't need this level of control and just need to inject the three dynamic values you could just use a template string.

history.push(`/search?param1=${value1}&param2=${value2}&param3=${value3}`);

Solution 2:[2]

How about this?

history.push('/search?param1=value1&param2=value2')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Youzef