What is client-storage
client-storageis 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 approachclient-storagecan 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 browserwindowis 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_STORAGEclass from"@orashus/client-storage"and create an instance of the kind of storage you'd like to use.- choose between
localfor localStorage andsessionfor sessionStorage
- choose between
import{CLIENT_STORAGE}from"@orashus/client-storage";constlocalStorage=newCLIENT_STORAGE("local");constsessionStorage=newCLIENT_STORAGE("session");NOTE!! For the rest of this guide, we'll be using the localStorage instance
Basic
constval=localStorage.get("test-key");// returns string by default
You could
parsethe value by setting the parse option totruelike soconstval=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
fallbackvalue by updating the fallback option like soconstval=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!
