jsonify-storage
Introduction
There is a unfriendly case when we use the the native localStorage
, such as
localStoragelocalStorage // => [object Object] localStoragelocalStorage // => '123'
So, jsonify it!
Install
⚠Notice: Can only works in browser environment, other scene need define global variable to mock
Storage
.
// In node you have to write like this. globallocalStorage = yourLocalStorageglobalsessionStorage = yourSessionStorage
Node:
npm i -D jsonify-storage
Browser:
Usage
Import in Node:
// es mode// or cjs modeconst local session =
In Browser:
const local session = jsonifyStorage
local
meanslocalStorage
session
meanssessionStorage
Then you can use it like this:
locallocal // => { a: 123 }locala === 123 // => true, will retain the type.
Payload will be json-stringified before save.
Raw data seems like this:
localStorage // => '{"a":123}'
If you try to get something can't parsed by JSON or not existed will return null
localStoragelocal // => nulllocal // => null
Others apis sames as native Storage
, list below.
- setItem -> set
- getItem -> get
- removeItem -> remove
- clear -> clear
- key -> key
- length -> length
More details see API documentation.