JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 506
  • Score
    100M100P100Q103074F
  • License MIT

Like useState hook but with persistance in storage

Package Exports

  • @plq/use-persisted-state

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@plq/use-persisted-state) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

#usePersistedState

Persists the state to localStorage, sessionStorage or anything else that implements getItem, setItem and removeItem

Example

import createPersistedState from '@plq/use-persisted-state'

const [usePersistedState] = createPersistedState('example')

export default function App() {
  const [count, setCount] = usePersistedState('count', 0)
  const handleIncrement = () => setCount(prevCount => prevCount + 1)

  return (
    <div>
      {count}
      <button onClick={handleIncrement}>+</button>
    </div>
  )
}

Requirement

To use @plq/use-persisted-state, you must use react@16.8.0 or greater which includes Hooks.

Clear Storage

import createPersistedState from '@plq/use-persisted-state'

const [usePersistedState, clear] = createPersistedState('example')

export default function App() {
  const [count, setCount] = usePersistedState('count', 0)
  const increment = () => setCount(prevCount => prevCount + 1)

  return (
    <div>
      {count}
      <button onClick={increment}>+</button>
      <button onClick={clear}>Clear</button>
    </div>
  )
}

Use sessionStorage

import createPersistedState from '@plq/use-persisted-state'

const [usePersistedState] = createPersistedState('example', window.sessionStorage)

export default function App() {
  const [count, setCount] = usePersistedState('count', 0)
  const increment = () => setCount(prevCount => prevCount + 1)

  return (
    <div>
      {count}
      <button onClick={increment}>+</button>
    </div>
  )
}

Use custom storage

import createPersistedState from '@plq/use-persisted-state'

const myStorage = {
  getItem: (key) => getItemFromSomeStorage(key)
  setItem: (key, value) => setItemToSomeStorage(key, value)
  removeItem: (key) => removeItemFromSomeStorage(key)
}

const [usePersistedState] = createPersistedState('example', myStorage)

export default function App() {
  const [count, setCount] = usePersistedState('count', 0)
  const increment = () => setCount(prevCount => prevCount + 1)

  return (
    <div>
      {count}
      <button onClick={increment}>+</button>
    </div>
  )
}

ToDo

  • Support async storage