// Retrieve params via url.search, passed into ctor
var url = new URL('https://example.com?foo=1&bar=2');
var params = new URLSearchParams(url.search);
// Pass in a string literal
var params2 = new URLSearchParams("foo=1&bar=2");
var params2a = new URLSearchParams("?foo=1&bar=2");
// Pass in a sequence of pairs
var params3 = new URLSearchParams([["foo", "1"], ["bar", "2"]]);
// Pass in a record
var params4 = new URLSearchParams({"foo": "1", "bar": "2"});
let params = new URLSearchParams('foo=2'); // "location.search" to read from URL
params.append('bar', 4); //Add a bar parameter.
console.log(params.toString()); //Prints 'foo=2&bar=4'
location.search = params.toString(); // write changes to URL
import React, { useEffect, useState } from "react";
import { useLocation } from "react-router-dom";
function CheckoutDetails() {
const location = useLocation();
const [amountValue, setAmountValue] = useState(1);
// function to get query params using URLSearchParams
useEffect(() => {
const searchParams = new URLSearchParams(location.search);
if (searchParams.has("amount")) {
const amount = searchParams.get("amount");
setAmountValue(parseInt(amount, 10));
} else {
setAmountValue(1);
}
}, [location]);
return (
<p>Amount: {amountValue}</p>
)
function buildParams(data) {
const params = new URLSearchParams()
Object.entries(data).forEach(([key, value]) => {
if (Array.isArray(value)) {
value.forEach(value => params.append(key, value.toString()))
} else {
params.append(key, value.toString())
}
});
return params.toString()
}