Skip to content

Repository files navigation

Welcome to @orashus/client-storage PKG

current versionauthor RashJrEdmund

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 browser window is not defined

table of content

Installation

To install run

# npm
npm install @orashus/client-storage
# pnpm
pnpm install @orashus/client-storage
# yarn
yarn add @orashus/client-storage

How to use

  • 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 and session for sessionStorage
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

  • Reading from storage

    • Basic

      constval=localStorage.get("test-key");// returns string by default
    • You could parse the value by setting the parse option to true like so

      constval=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 so

      constval=localStorage.get("another-key",{fallback: ""});// Will return fallback if an error occurs or window is not defined

    Writing to storage

    • As simple as

      localStorage.save("key",{value: "pair"});// value will be stringified under the hood if it is not a string

    Removing from storage

    • Remove items from storage with

      localStorage.remove("key");// clears value from storage

    Clearing all items from storage

    • Remove all items from storage with

      localStorage.clear();// clears everything within storage

|

happy coding!

About

localStorage or sessionStorage browser API with a wrapper. Install with `npm i @orashus/client-storage`

Topics

Resources

Contributing

Security policy

Stars

2 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages