Last active
July 25, 2022 16:55
-
-
Save erenkulaksiz/dc6e1b710ce14f7a81a335516ecc13e8 to your computer and use it in GitHub Desktop.
Localstorage implementation for NextJS used in Notal
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 { isClient } from "@utils/isClient"; // check for Serverside rendering | |
interface DefaultSettingsTypes { | |
cookies: boolean; | |
installedVersion: string; | |
installedEnv: string; | |
navbarCollapsed: boolean; | |
} | |
const DefaultSettings: DefaultSettingsTypes = { | |
cookies: false, | |
installedVersion: process.env.NEXT_PUBLIC_APP_VERSION || "", | |
installedEnv: process.env.NODE_ENV, | |
navbarCollapsed: false, | |
}; | |
export const LocalSettings: { | |
get: (key: string) => any | undefined; | |
set: (key: string, value: any) => void; | |
} = { | |
get: function (item: string) { | |
if (!isClient()) return undefined; | |
const Local = localStorage.getItem("settings"); | |
if (typeof Local == "undefined" || !Local) { | |
// set defaults if not exist | |
localStorage.setItem("settings", JSON.stringify(DefaultSettings)); | |
return DefaultSettings[key as keyof DefaultSettingsTypes]; // return default data | |
} else { | |
try { | |
const LocalItem = JSON.parse(Local); | |
if (typeof LocalItem[item] == "undefined") { | |
localStorage.setItem("settings", JSON.stringify(DefaultSettings)); | |
return DefaultSettings[key as keyof DefaultSettingsTypes]; | |
} | |
return LocalItem[key]; | |
} catch (error) { | |
localStorage.setItem("settings", JSON.stringify(DefaultSettings)); | |
return DefaultSettings[key as keyof DefaultSettingsTypes]; | |
} | |
} | |
}, | |
set: function (key: string, value: any) { | |
if (!isClient()) return undefined; | |
const Local = localStorage.getItem("settings"); | |
if (typeof Local == "undefined" || !Local) { | |
// set defaults if not exist | |
localStorage.setItem("settings", JSON.stringify(DefaultSettings)); | |
} else { | |
// After applying defaults | |
try { | |
const NewLocal = JSON.parse(Local); | |
NewLocal[key] = value; | |
localStorage.setItem("settings", JSON.stringify(NewLocal)); | |
} catch (error) { | |
localStorage.setItem("settings", JSON.stringify(DefaultSettings)); | |
} | |
} | |
}, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage in any react component
import LocalSettings
then set any value
and get any value
Note: You can not use this helper with SSR. Returns
undefined
, because localstorage is not available in server side as well as object window.