Created
April 11, 2024 16:39
-
-
Save baptistemanson/9230ffa1211f38012ecdea17bcebd574 to your computer and use it in GitHub Desktop.
history provider for next
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 { 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