Answer the question
In order to leave comments, you need to log in
How to properly remove parameters from url string in react-router-dom?
I'm trying to make a function that will toggle the parameter in the url to change the checkbox. Everything works, but I can't change them in the loop. It is necessary to achieve the behavior when I loop through all the selected parameters, delete the ones that are not needed in the condition, while leaving the rest.
Now my function that adds / removes a parameter looks like this:
const updateFiltersSearchParams = (paramKey, newValue) => {
const isParamExist = searchParams.getAll(paramKey).includes(newValue);
if (!isParamExist) {
searchParams.append(paramKey, newValue);
setSearchParams(searchParams);
} else {
const updatedSearchParams = new URLSearchParams(
[...searchParams].filter(
([key, value]) => key !== paramKey || value !== newValue
)
);
setSearchParams(updatedSearchParams);
}
};
const [searchParams, setSearchParams] = useSearchParams();
const checkboxParams = searchParams.getAll("selected");
const handleDeleteParams = () => {
[...checkboxParams].forEach((param) => {
updateFiltersSearchParams("selected", param);
});
};
Answer the question
In order to leave comments, you need to log in
const toggleSearchParams = params => {
const newSearchParams = [...searchParams];
for (const n of params) {
const index = newSearchParams.findIndex(m => n[0] === m[0] && n[1] === m[1]);
if (index === -1) {
newSearchParams.push(n);
} else {
newSearchParams.splice(index, 1);
}
}
setSearchParams(newSearchParams);
};
const handleChangeCheckBoxValue = e => {
toggleSearchParams([ [ 'selected', e.target.value ] ]);
};
const handleDeleteParams = () => {
toggleSearchParams(checkboxParams.map(n => [ 'selected', n ]));
};
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question