V
V
Viktor Putin2022-01-12 16:15:34
JavaScript
Viktor Putin, 2022-01-12 16:15:34

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);
    }
  };


This is how I try to remove multiple options
const [searchParams, setSearchParams] = useSearchParams();
 const checkboxParams = searchParams.getAll("selected");

 const handleDeleteParams = () => {
    [...checkboxParams].forEach((param) => {
      updateFiltersSearchParams("selected", param);
    });
  };


I am using react-router-dom 6
Sandbox

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2022-01-12
@Ambi2Rush

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 question

Ask a Question

731 491 924 answers to any question