How do I add additional queryParams to current URL?

Viewed 34

I am using React's use history hook to create query params in URL. After filling out a name and clicking a button, my URL changes from "xyz.com/#/customer" to "xyz.com/#customer?name=rabin". Then, after some background processing from an API, we get their phone number. I would like to add the phone number to currentUrl like

"xyz.com/#customer?name=rabin&phone=682222333".

I tried the following approach.

  1. history.push(phone=${phone}) -> Result = "xyz.com/#customer?&phone=682222333"
  2. history.push(pathname: window.location.hash.substring(2), search=phone=${phone}) -> Result = "xyz.com/#customer?name=rabin&?phone=682222333"

I am not able to create this "xyz.com/#customer?name=rabin&phone=682222333". Please help. I have been stuck on this for 3 days.

1 Answers

Create a URLSearchParams object from the current location.search value. You can then mutate the searchParams object and issue an imperative navigation with the updated queryString.

Example:

const { search } = useLocation();
const history = useHistory();

const searchParams = useMemo(() => new URLSearchParams(search), [search]);

...

searchParams.set("phone", "682222333");
history.push({
  pathname: "/customer",
  search: searchParams.toString();
});
// or history.push(`/customer?${searchParams.toString()}`);
Related