Install
yarn add jrestore
Basic usage
jrestore
not only converts your regular string-oriented localStorage
into a JSON storage, you can also subscribe to changes. It makes use of localStorage
in the background, so everything is persistent. It can be used with or without React.
import jrestore from 'jrestore'
jrestore.setItem('mykey', { a: 12, b: true })
console.log(
jrestore.getItem('mykey')
)
jrestore.removeItem('mykey')
console.log(
jrestore.getItem('mykey')
)
jrestore.setItem('mykey', [1, 2, 3])
jrestore.clear()
console.log(
jrestore.getItem('mykey')
)
jrestore.setItem('mykey', 0)
jrestore.setItem('mykey', value => value + 1)
Events
const listener = value => console.log('Value changed :', value)
jrestore.addListener('mykey', listener)
jrestore.setItem('mykey', -452)
jrestore.setItem('mykey', [1, 2])
jrestore.setItem('mykey', arr => [...arr, 3])
jrestore.clear()
jrestore.setItem('mykey', true)
jrestore.removeItem('mykey')
jrestore.removeListener('mykey', listener)
jrestore.setItem('mykey', -452)
Usage with React
import React from 'react
import jrestore from 'jrestore'
jrestore.React = React // Don't forget !
const ComponentA = () => {
const counter = jrestore.useItem('counter')
return (
<button onClick={() => jrestore.setItem('counter', counter + 1)}>
Increment {counter}
</button>
)
}
const ComponentB = () => {
const counter = jrestore.useItem('counter', 0)
return (
<button onClick={() => jrestore.setItem('counter', counter + 1)}>
Increment {counter}
</button>
)
}
const ComponentC = () => (
<button onClick={() => jrestore.setItem('counter', counter => counter + 1)}>
Increment
</button>
)
const ComponentD = () => {
const object = jrestore.useItem('myobj', { a: 12, b: [true] })
if(!object)
return <b>Object was removed</b>
return (
<button onClick={() => jrestore.removeItem('myobj')}>
Remove
</button>
)
}
Settings
jrestore.prefix = 'myprefix'
jrestore.React = React
jrestore.store = window.localStorage
jrestore.serialize = JSON.stringify
jrestore.deserialize = JSON.parse