Skip to content

Instantly share code, notes, and snippets.

@baptistemanson
Created April 11, 2024 16:39
Show Gist options
  • Save baptistemanson/9230ffa1211f38012ecdea17bcebd574 to your computer and use it in GitHub Desktop.
Save baptistemanson/9230ffa1211f38012ecdea17bcebd574 to your computer and use it in GitHub Desktop.
history provider for next
import { atomWithStorage, createJSONStorage } from "jotai/utils";
const storage = createJSONStorage(() => sessionStorage);
export const historyAtom = atomWithStorage(
"history",
[window.location.href],
storage
);
// will give you access to the history in the component you wish
export const HistoryProvider = ({ children }) => {
const router = useRouter();
const [setHistory] = useAtom(historyAtom);
useEffect(() => {
const handleRouteChange = (url) => {
setHistory((history) => {
if (history[history.length - 1] !== url) return [...history, url];
else return history;
});
};
router.events.on("routeChangeComplete", handleRouteChange);
return () => {
router.events.off("routeChangeComplete", handleRouteChange);
};
}, [router.events]);
return children;
};
// in index.tsx
// <Root><HistoryProvider>... </HistoryProvider></Root>;
// in the component you want the history for a process
const MyComponent = () => {
const [history] = useAtom(historyAtom);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment