Socket
Book a DemoInstallSign in
Socket

@singletn/local-storage

Package Overview
Dependencies
Maintainers
1
Versions
18
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@singletn/local-storage

## Persist your data

latest
Source
npmnpm
Version
0.0.18
Version published
Maintainers
1
Created
Source

@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

FAQs

Package last updated on 15 Aug 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts