DEV Community

Natserract
Natserract

Posted on

Local Storage Running in Observer

Called localStorageObserver this is a simple storage library for JavaScript, get inspire from localForage but running as Observer. This library support TypeScript, and EasyTo-Use.

Problems why created this library:

window.addEventListener('storage', () => {})
Enter fullscreen mode Exit fullscreen mode

This won't work on the same page that is making the changes — it is really a way for other pages on the domain using the storage to sync any changes that are made. Pages on other domains can't access the same storage objects. https://developer.mozilla.org/en-US/docs/Web/API/Window/storage_event

How to use

To use localStorageObserver, just drop a single line into your app:

import localStorageObserver from 'local-storage-observer'
Enter fullscreen mode Exit fullscreen mode

See more real example.

Download the latest localStorageObserver from GitHub, or install with npm:

npm install local-storage-observer
Enter fullscreen mode Exit fullscreen mode

Configuration

You can set several configuration with the config() method. Avalaible options description, storeName, and version (use for future, currently isn't some affect in your app).

Example:

localStorageObserver.config({
  storeName: 'local_storage_observer',
})
Enter fullscreen mode Exit fullscreen mode

Note: you must call config() before you interact with your data. This means calling config() before using get$(), or set$().

Get Item

Gets an item from the local storage and supplies the result to a subscriber. If the key does not exist, get\$() will return null.

localStorageObserver.get$(key).subscribe((next) => {
  console.log('Result', JSON.parse(next))
})
Enter fullscreen mode Exit fullscreen mode

Note: localStorageObserver doesn't store the value null / undefined.

Set Item

Saves data to local storage.

localStorageObserver.set$(key, values).subscribe((next) => {
  console.log('Step two, set$', next)
})
Enter fullscreen mode Exit fullscreen mode

You can store the following types of JavaScript objects:

  • Array
  • String
  • Number
  • Object

Remove Item

Removes the value of a key from the local storage.

localStorageObserver.remove$(key).subscribe({
  next: (message) => console.log('Message: ', message),
  error: (error) => console.error('Error: ', error),
})
Enter fullscreen mode Exit fullscreen mode

Clear Item

Removes the value of a key from the local storage.

localStorageObserver.clear$().subscribe((message) => {
  console.log('Message: ', message)
})
Enter fullscreen mode Exit fullscreen mode

Unsubscribe

Cleanup a subscription

useEffect(() => {
  ...

  return () => {
    localStorageObserver.destroySubscription$()
  }
}, [])
Enter fullscreen mode Exit fullscreen mode

Install package on: https://www.npmjs.com/package/local-storage-observer

Top comments (0)