What is client-storage
-
client-storage
is a simple wrapper around the browser's localStorage and sessionStorage APIs, it abstracts the lengthy "localStorage.getItem()" etc ways of accessing local or session storage, adds more functionality to these methods like you can configure for automatic parsing. It also comes with a type safe approach -
client-storage
can also help in server rendered applications such as those built with NextJs In that, you could decide to have a fall-back value for what ever data you are getting from storage, this way, it won't throw an error on the server if the browserwindow
is not defined
table of content
- installation
- how to use
- personal notes # a few notes on my findings
To install run
# npm
npm install @orashus/client-storage
# pnpm
pnpm install @orashus/client-storage
# yarn
yarn add @orashus/client-storage
- First import the
CLIENT_STORAGE
class from"@orashus/client-storage"
and create an instance of the kind of storage you'd like to use.- choose between
local
for localStorage andsession
for sessionStorage
- choose between
import { CLIENT_STORAGE } from "@orashus/client-storage";
const localStorage = new CLIENT_STORAGE("local");
const sessionStorage = new CLIENT_STORAGE("session");
NOTE!! For the rest of this guide, we'll be using the localStorage
instance
-
-
Basic
const val = localStorage.get("test-key"); // returns string by default
-
You could
parse
the value by setting the parse option totrue
like soconst val = localStorage.get("test-key", { parse: true }); // this will attempt to execute JSON.parse() on the read value // and will throw error if value is not a valid JSON
-
You could also assign a
fallback
value by updating the fallback option like soconst val = localStorage.get("another-key", { fallback: "" }); // Will return fallback if an error occurs or window is not defined
-
As simple as
localStorage.save("key", { value: "pair" }); // value will be stringified under the hood if it is not a string
-
Remove items from storage with
localStorage.remove("key"); // clears value from storage
-
Remove all items from storage with
localStorage.clear(); // clears everything within storage
-
|
happy coding!