Skip to content

Instantly share code, notes, and snippets.

@tekno0ryder
Created May 3, 2023 16:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tekno0ryder/f25158983647978013979ce3aa6bba49 to your computer and use it in GitHub Desktop.
Save tekno0ryder/f25158983647978013979ce3aa6bba49 to your computer and use it in GitHub Desktop.
A custom hook to save last query search in local storage
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