0.0.17 • Published 3 months ago

@singletn/local-storage v0.0.17

Weekly downloads
-
License
MIT
Repository
github
Last release
3 months ago

@singletn/local-storage npm version

Persist your data

If you'd like to have a persistent state in your localStorage, you can do so by having your state extend LocalStorageSingletn.

When extending LocalStorageSingletn, there's a small requirement you need to follow: you need to have a constructor method in your state, that calls super() with the initial state. Here's how your state would look like with LocalStorageSingletn:

import { LocalStorageSingletn } from '@singletn/local-storage'

interface UserState {
  name: string
  email: string
  phoneNumber: string
}

export class User extends LocalStorageSingletn<UserState> {
  constructor() {
    // First parameter is used to prefix all the keys for this singletn.
    // Make sure this key is unique to avoid having broken data.
    super('userData', {
      name: '',
      email: '',
      phoneNumber: '',
    })
  }

  public setUser = (user: UserState) => this.setState(user)

  public setName = (name) => this.setState({ name })

  public setEmail = (email) => this.setState({ email })

  // ...
}

The constructor is necessary so that the initial state can use the stored data keys and have the default values as fallbacks. The constructor params are:

NameDescription
singletnKeyUnique key to be used to prefix all keys on local storage that refers to this singletn
initialStateA state to be used as a fallback for when the local storage does not contain any definition for the keys expected from the state
0.0.17

3 months ago

0.0.10

10 months ago

0.0.11

10 months ago

0.0.12

9 months ago

0.0.13

8 months ago

0.0.14

8 months ago

0.0.15

7 months ago

0.0.9

10 months ago

0.0.16

7 months ago

0.0.8

10 months ago

0.0.7

10 months ago

0.0.5

1 year ago

0.0.4

1 year ago

0.0.6

1 year ago

0.0.3

1 year ago

0.0.2

1 year ago

0.0.1

1 year ago