Skip to content

Instantly share code, notes, and snippets.

@uguisu-an
Last active March 30, 2022 18:26
Show Gist options
  • Save uguisu-an/21cac4ea31eb21d224a77f5c156c02cb to your computer and use it in GitHub Desktop.
Save uguisu-an/21cac4ea31eb21d224a77f5c156c02cb to your computer and use it in GitHub Desktop.
React-Router: useSearchParamsの更新を助けるカスタムフック
import { useSearchParams } from "react-router-dom";
export const useSetSearchParam =
(...[searchParams, setSearchParams]: ReturnType<typeof useSearchParams>) =>
(key: string) =>
(value: string) => {
const newSearchParams = new URLSearchParams(searchParams);
newSearchParams.set(key, value);
setSearchParams(newSearchParams);
};
export const useSetSearchParamArray =
(...[searchParams, setSearchParams]: ReturnType<typeof useSearchParams>) =>
(key: string) =>
(values: string[]) => {
const newSearchParams = new URLSearchParams(searchParams);
newSearchParams.delete(key);
values.forEach((value) => {
newSearchParams.append(key, value);
});
setSearchParams(newSearchParams);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment