@grnx-utils/local-storage
TypeScript icon, indicating that this package has built-in type declarations

0.1.0 • Public • Published

@grnx-utils/local-storage

npm version PRs Welcome

Provides a convenient API for working with localStorage.

Features:

  • Automatic parsing if the value is in JSON format
  • Automatic JSON.stringify if you want to set non-primitive type to localStorage
  • Next.js support (check if typeof window !== 'undefined')
  • Ability to add a prefix to keys (useful if you have several applications on the same domain. For example, turns AUTH_TOKEN into myapp__AUTH_TOKEN)
  • Ability to disable setting new values if necessary
  • LocalStorage key typing (with typescript)

Installation

yarn add @grnx-utils/local-storage -D

Basic Usage

import { createStorage } from '@grnx-utils/local-storage'

export enum LocalStorage {
    someKey = 'someKey'
}

const storage = createStorage<LocalStorage>({
    layer: 'my-app'
})
storage.set('someKey', {
    someKey: 'value'
})

storage.get('someKey') // { someKey: 'value' }

storage.clear('someKey')

storage.get('someKey') // void

storage.disable() // will stop work

Comparison with regular localStorage

// @grnx-utils/local-storage

storage.set('someKey', {
    someKey: 'value'
})

// common localStorage

if (typeof window !== 'undefined') {
    localStorage.setItem(
        'my-app__someKey',
        JSON.stringify({
            someKey: 'value'
        })
    )
}

Configure API

const storage = createStorage<LocalStorage>({
    /** Application layer
     * @type string
     * @default - undefined
     */
    layer: 'my-app',
    /**
     * @type boolean
     * @default - false
     */
    isDisabled: true
})

Package Sidebar

Install

npm i @grnx-utils/local-storage

Weekly Downloads

0

Version

0.1.0

License

none

Unpacked Size

6.61 kB

Total Files

10

Last publish

Collaborators

  • gearonix