Last active
November 5, 2023 12:19
-
-
Save simonrelet/483e87cdc054c8b42892b43fd6db2174 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 { useLocation, useNavigation, useSearchParams } from "@remix-run/react"; | |
import { useCallback, useMemo } from "react"; | |
export function useOptimisticSearchParams() { | |
const location = useLocation(); | |
const [searchParams, setSearchParams] = useSearchParams(); | |
const navigation = useNavigation(); | |
const nextSearchParams = useMemo(() => { | |
if (navigation.location?.pathname === location.pathname) { | |
return new URLSearchParams(navigation.location.search); | |
} | |
return undefined; | |
}, [ | |
location.pathname, | |
navigation.location?.pathname, | |
navigation.location?.search, | |
]); | |
const optimisticSearchParams = nextSearchParams ?? searchParams; | |
// When the set state function is called with a function, it needs to recieve | |
// the optimistic search parameters. | |
const setOptimisticSearchParams = useCallback<typeof setSearchParams>( | |
(nextInit, navigateOptions) => { | |
setSearchParams( | |
typeof nextInit === "function" | |
? nextInit( | |
// Pass `nextInit` a copy so it can safely mutate it. | |
new URLSearchParams(optimisticSearchParams), | |
) | |
: nextInit, | |
navigateOptions, | |
); | |
}, | |
[optimisticSearchParams, setSearchParams], | |
); | |
return [optimisticSearchParams, setOptimisticSearchParams] as const; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment