Skip to content

Instantly share code, notes, and snippets.

@erenkulaksiz
Last active July 25, 2022 16:55
Show Gist options
  • Save erenkulaksiz/dc6e1b710ce14f7a81a335516ecc13e8 to your computer and use it in GitHub Desktop.
Save erenkulaksiz/dc6e1b710ce14f7a81a335516ecc13e8 to your computer and use it in GitHub Desktop.
Localstorage implementation for NextJS used in Notal
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));
}
}
},
};
@erenkulaksiz
Copy link
Author

Usage in any react component

import LocalSettings

import { LocalSettings } from "@utils";

then set any value

LocalSettings.set("seen", true);

and get any value

LocalSettings.get("seen");

Note: You can not use this helper with SSR. Returns undefined, because localstorage is not available in server side as well as object window.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment