Skip to content

Commit

Permalink
feat: Add swr cache (#437)
Browse files Browse the repository at this point in the history
* feat: adds localstorage provider to cache

fix #308

* npm run format
  • Loading branch information
bdougie committed Sep 30, 2022
1 parent d864809 commit 6b2b1cb
Showing 1 changed file with 26 additions and 2 deletions.
28 changes: 26 additions & 2 deletions pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ type ComponentWithPageLayout = AppProps & {

function MyApp({ Component, pageProps }: ComponentWithPageLayout) {
const router = useRouter();

// From documentation on using Posthog with Next.js: https://posthog.com/docs/integrate/third-party/next-js
useEffect(() => {
initiateAnalytics();
Expand All @@ -36,6 +36,29 @@ function MyApp({ Component, pageProps }: ComponentWithPageLayout) {

const { filterName, toolName } = router.query;

function localStorageProvider() {
if (typeof window !== "undefined") {
console.log("You are on the browser");

// When initializing, we restore the data from `localStorage` into a map.
const map = new Map(JSON.parse(localStorage.getItem("app-cache") || "[]"));

// Before unloading the app, we write back all the data into `localStorage`.
window.addEventListener("beforeunload", () => {
const appCache = JSON.stringify(Array.from(map.entries()));
localStorage.setItem("app-cache", appCache);
});

// We still use the map for write & read for performance.
return map;
} else {
console.log("You are on the server");
// 👉️ can't use localStorage

return new Map();
}
}

supabase.auth.onAuthStateChange((event, session) => {
fetch("/api/auth", {
method: "POST",
Expand Down Expand Up @@ -64,7 +87,8 @@ function MyApp({ Component, pageProps }: ComponentWithPageLayout) {
<SWRConfig
value={{
revalidateOnFocus: false,
fetcher: apiFetcher
fetcher: apiFetcher,
provider: localStorageProvider
}}
>
<GlobalState>
Expand Down

0 comments on commit 6b2b1cb

Please sign in to comment.