There is a problem with deleting several string parameters. Only the last parameter is being deleted now.
upd: I did not specify that I wanted to achieve the ability to remove specific parameter values
this code does not work correctly:
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 handleDeleteParams = () => { [...checkboxParams].forEach((param) => { updateFiltersSearchParams("selected", param); }); };
Advertisement
Answer
Solved the problem by modifying the function like this
const toggleSearchParams = (params) => { const newSearchParams = [...searchParams]; for (const prevParam of params) { const index = newSearchParams.findIndex( (newParam) => prevParam[0] === newParam[0] && prevParam[1] === newParam[1] ); if (index === -1) { newSearchParams.push(prevParam); } else { newSearchParams.splice(index, 1); } } setSearchParams(new URLSearchParams(newSearchParams)); }; const handleChangeCheckBoxValue = (e) => { toggleSearchParams([["selected", e.target.value]]); }; const handleDeleteParams = () => { toggleSearchParams(checkboxParams.map((param) => ["selected", param])); };