Last active
March 30, 2022 18:26
-
-
Save uguisu-an/21cac4ea31eb21d224a77f5c156c02cb to your computer and use it in GitHub Desktop.
React-Router: useSearchParamsの更新を助けるカスタムフック
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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