Created
May 3, 2023 16:31
-
-
Save tekno0ryder/f25158983647978013979ce3aa6bba49 to your computer and use it in GitHub Desktop.
A custom hook to save last query search in local storage
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 { useEffect } from "react"; | |
import { useLocation } from "react-router"; | |
import { useNavigate } from "react-router-dom"; | |
import { useLocalStorage } from "usehooks-ts"; | |
// A hook to save last search query and load it again when `loadLastSearch` is received in location state | |
// Useful to save table state and load it when user click on custom in-page back button | |
export const useLastSearch = (key: string, isDisabled?: boolean) => { | |
const [lastSearch, setLastSearch] = useLocalStorage(`${key}/last-search`, ""); | |
const location = useLocation(); | |
const navigate = useNavigate(); | |
useEffect(() => { | |
if (isDisabled) { | |
return; | |
} | |
if (location.state?.loadLastSearch) { | |
navigate(location.pathname + lastSearch, { replace: true }); | |
} else { | |
setLastSearch(location.search); | |
} | |
}, [isDisabled, lastSearch, location, navigate, setLastSearch]); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment