I have multi-checkbox inputs. if checked, I want set query params like this:
topic[]=1&topic[]=2&...
please help me resolve this problem
this is my code for unique param:
const addQueryParam = (name, value) => {
const urlParam = new URL(window.location.href);
if (!value) {
urlParam.searchParams.delete(name);
} else {
urlParam.searchParams.set(name, value);
}
window.history.pushState({ path: urlParam.href }, "", urlParam.href);
};
You can build the query params with something like this:
// Values I want to pass by queryParams
const params = { name: 'Jhons', multiCheckbox: [1, 2, 3], ...otherValues};
Then I go through the object to build the string that I will pass to the query params
let queryParams = '';
Object.keys(params).map(key => {
if (Array.isArray(params[key])) {
queryParams += params[key].map((value) => `${key}[]=${value}`).join('&')
}
queryParams += `${key}=${params[key]}&`
})
Print the queryParams to get something like this:
'name=Jhons&multiCheckbox[]=1&multiCheckbox[]=2&multiCheckbox[]=3'