Skip to content

Interface: IStore<Key, Value, CacheDisabled> ​

Defined in: store/src/types/IStore.ts:85

Represents a generic, reactive, and persistent Map-like data store.

The IStore interface defines the contract for a data structure that combines the standard functionality of a JavaScript Map with advanced features such as RxJS-powered reactivity, optional persistence (e.g., to LocalStorage or a JSON file), and built-in search, sorting, and filtering.

It is designed to be framework-agnostic but provides features that integrate well with reactive systems and modern UI libraries like React.

Type Parameters ​

Key ​

Key

The type of keys used to identify values in the store.

Value ​

Value

The type of values stored in the store.

CacheDisabled ​

CacheDisabled extends boolean = false

A boolean flag; if true, the store operates without an in-memory cache, reading and writing directly to the underlying storage on every operation.

Properties ​

cacheDisabled ​

readonly cacheDisabled: CacheDisabled

Defined in: store/src/types/IStore.ts:87

Disable in-memory cache and only directly read/write from storage (local storage or JSON fle)


clear ​

readonly clear: () => IStore<Key, Value, CacheDisabled>

Defined in: store/src/types/IStore.ts:273

Clear all items

Returns ​

IStore<Key, Value, CacheDisabled>


delay ​

readonly delay: number

Defined in: store/src/types/IStore.ts:97

Debounce/throttle delay duration in milliseconds for writing to storage when caching is enabled.

Increasing this value can improve performance when dealing with large datasets or frequent updates by reducing the number of write operations.

Default: 300


delayOptions? ​

readonly optional delayOptions?: Store_DelayOptions

Defined in: store/src/types/IStore.ts:100

Debounce and throttle related options


delete ​

readonly delete: (key) => IStore<Key, Value, CacheDisabled>

Defined in: store/src/types/IStore.ts:276

Delete one or more items by their respective keys

Parameters ​

key ​

Key | Key[]

Returns ​

IStore<Key, Value, CacheDisabled>


entries ​

readonly entries: () => [Key, Value][]

Defined in: store/src/types/IStore.ts:279

Get entries (2D Array)

Returns ​

[Key, Value][]


filter ​

readonly filter: <AsArray>(...args) => AsArray extends true ? Map<Key, Value> : Value[]

Defined in: store/src/types/IStore.ts:282

Filter items by predicate

Type Parameters ​

AsArray ​

AsArray extends boolean = false

Parameters ​

args ​

...[FilterPredicate<Key, Value>, number, AsArray, Map<Key, Value>]

Returns ​

AsArray extends true ? Map<Key, Value> : Value[]


find ​

readonly find: <IncludeKey>(predicateOrOptions) => IncludeKey extends true ? [Key, Value] : Value | undefined

Defined in: store/src/types/IStore.ts:287

Find an item by predicate or search criteria

Type Parameters ​

IncludeKey ​

IncludeKey extends boolean = false

Parameters ​

predicateOrOptions ​

FilterPredicate<Key, Value> | FindOptions<Key, Value, IncludeKey>

Returns ​

IncludeKey extends true ? [Key, Value] : Value | undefined


get ​

readonly get: (key) => Value | undefined

Defined in: store/src/types/IStore.ts:294

Get item by key

Parameters ​

key ​

Key

Returns ​

Value | undefined


getAll ​

readonly getAll: (forceUpdate?, silent?) => Map<Key, Value>

Defined in: store/src/types/IStore.ts:308

Get all items

Parameters ​

forceUpdate? ​

boolean

(optional) if true and cache is enabled, reads & updates data directly from storage

Default: false

silent? ​

boolean

(optional) Whether to throw error on failure.

Default: true

Returns ​

Map<Key, Value>

data map


has ​

readonly has: (key) => boolean

Defined in: store/src/types/IStore.ts:314

Check if key exists

Parameters ​

key ​

Key

Returns ​

boolean


init ​

readonly init: (initialValue?, silent?) => boolean

Defined in: store/src/types/IStore.ts:331

Initializes storage and sets up internal subscriptions.

Manual invocation is not typically necessary, as initialization occurs automatically in one of the following scenarios:

  • During construction, if an initialValue with at least one entry is provided.
  • On the first attempt to read or write data.

Parameters ​

initialValue? ​

Map<Key, Value>

(optional) An optional map to initialize the storage with if it's currently empty.

silent? ​

boolean

(optional) Whether to throw error on failure.

Default: true

Returns ​

boolean

true if initialization was successful, or false if the storage was already initialized.


initialized ​

readonly initialized: boolean

Defined in: store/src/types/IStore.ts:105

Indicates wherether storage has been initialized (init() function invoked).


keys ​

readonly keys: () => Key[]

Defined in: store/src/types/IStore.ts:334

Get all keys

Returns ​

Key[]


map ​

readonly map: <T>(callback) => T[]

Defined in: store/src/types/IStore.ts:337

Map each item on the data to an Array

Type Parameters ​

T ​

T = unknown

Parameters ​

callback ​

(value, key, entries, index) => T

Returns ​

T[]


name? ​

readonly optional name?: string | null

Defined in: store/src/types/IStore.ts:113

Storage name. Filename (NodeJS) or property name (browser LocalStorage). If empty string or undefined, data will not be saved to storage and will only work in-memory.

Default: null


onChange? ​

optional onChange?: (this, data) => ValueOrPromise<void | Map<Key, Value>>

Defined in: store/src/types/IStore.ts:182

A callback function executed whenever a data change occurs within the storage.

This hook allows for reactive side-effects. If the callback throws an error or returns a rejected Promise, the exception is caught gracefully and redirected to the onError callback with the type Store_OnErrorType.onChange.

Note: Execution of this callback is managed by internal subscriptions and will stop firing once unsubscribe is called.

Parameters ​

this ​

IStore<Key, Value, CacheDisabled>

data ​

Map<Key, Value>

Returns ​

ValueOrPromise<void | Map<Key, Value>>


onError? ​

optional onError?: (this, err, type) => ValueOrPromise<void>

Defined in: store/src/types/IStore.ts:198

A global error handler invoked whenever an internal operation fails.

It captures failures in the following areas:

  • Data parsing and serialization (JSON or custom logic).
  • Storage access (e.g., localStorage quota or permission errors).
  • Execution of user-provided callbacks like onChange.

Note: If this handler itself throws an error, the exception is ignored gracefully to prevent application crashes during storage cycles.

Parameters ​

this ​

IStore<Key, Value, CacheDisabled>

err ​

unknown

type ​

Store_OnErrorType

Returns ​

ValueOrPromise<void>


parse? ​

optional parse?: Store_Parse<Map<Key, Value>, IStore<Key, Value, CacheDisabled>>

Defined in: store/src/types/IStore.ts:220

A callback to customize the deserialization of data read from storage.

This allows you to transform the raw string from the underlying storage back into a Map<Key, Value>. It serves as the functional inverse of stringify.

Fallback Behavior:

  • If this function is not defined, or returns undefined or a non-map value, the system falls back to internal JSON.parse logic.
  • If the function throws an error, it will use and empty map.

Error Triggers:


read ​

readonly read: (dataStr?, silent?) => Map<Key, Value>

Defined in: store/src/types/IStore.ts:362

Reads and parses data directly from the persistent storage medium.

This operation is synchronous and does not trigger reactive updates via subject$. It is useful for debugging custom parse logic or manual data retrieval.

If instance.parse function is provided and invokation fails, an empty Map will be returned.

Parameters ​

dataStr? ​

string | null

(optional) A raw string to parse. If omitted, the method fetches the current value associated with the instance name from the underlying storage.

Default: null

silent? ​

boolean

(optional) Whether to throw error on failure.

Default: false

Returns ​

Map<Key, Value>


readonly search: <MatchExact, AsMap>(...args) => AsMap extends true ? Map<Key, Value> : Value[]

Defined in: store/src/types/IStore.ts:393

Search through the stored data (Map<Key, Value>). It supports both a global search (using a string or RegExp) across all properties of an item, and a detailed, field-specific search using a query object.

Type Parameters ​

MatchExact ​

MatchExact extends boolean = false

AsMap ​

AsMap extends boolean = true

Parameters ​

args ​

...[SearchOptions<Key, Value, MatchExact, AsMap>]

Returns ​

AsMap extends true ? Map<Key, Value> : Value[]

A Map or an Array containing the matched items, based on the asMap option.

Example ​

Search for users in a specific city ​

javascript
import { Store } from '@superutils/store'

const storage = new Store('users', {
  initialValue: new Map([
    [1, { name: 'John Doe', city: 'New York' }],
    [2, { name: 'Jane Doe', city: 'London' }],
    [3, { name: 'Peter Jones', city: 'New York' }],
  ])
})

const nyUsers = storage.search({ query: { city: 'New York' } })
console.log(nyUsers.size) // 2

set ​

readonly set: (key, value, silent?) => IStore<Key, Value, CacheDisabled>

Defined in: store/src/types/IStore.ts:421

Set item by key

Parameters ​

key ​

Key

value ​

Value | ((currentValue?) => Value)

value or function

silent? ​

boolean

(optional) Whether to throw error on failure.

Default: true

Returns ​

IStore<Key, Value, CacheDisabled>

Example ​

javascript
import { Store } from '@superutils/store'

const store = new Store<string, number>()
store.set('count', 1)
store.set('count', (prevCount = 0) => prevCount + 1)

setAll ​

readonly setAll: (data, replace?, silent?, validated?) => IStore<Key, Value, CacheDisabled>

Defined in: store/src/types/IStore.ts:443

Set multiple entries at once and/or replace the storage entries

Parameters ​

data ​

Map<Key, Value>

(optional) Data to add. Default: new Map()

replace? ​

boolean

(optional) Whether to merge with or replace current data.

  • true: replace all entries with data
  • false: merge with current data (existing entries with matching keys will be overwritten)

Default: false

silent? ​

boolean

(optional) Whether to throw error on failure.

Default: true

validated? ​

boolean

Returns ​

IStore<Key, Value, CacheDisabled>

store instance


size ​

readonly size: number

Defined in: store/src/types/IStore.ts:116

Get the number of items


sort ​

readonly sort: Store_Sort<Key, Value>

Defined in: store/src/types/IStore.ts:462

Sort items in the storage.

Param ​

nameOrComparator

Criteria to sort by. Accepts one of the following:

  • function: A comparator function to sort the data.
  • string: A property name of the value object to sort by.
  • true: Sorts the map by its keys.

Param ​

options

(optional) Sorting options.

Param ​

options.save

(optional) Whether to save the sorted data back to storage (localStorage/file).

Returns ​

The sorted Map.


spaces? ​

optional spaces?: number

Defined in: store/src/types/IStore.ts:119

Number of spaces to use when stringifying. Default: undefined


storage? ​

readonly optional storage?: Storage | StorageCompact | null

Defined in: store/src/types/IStore.ts:139

LocalStorage or equivalent storage instance to be used as the underlying storage and to read & write from.

Notes:

  • Ignored when name is falsy (in-memory only mode)
  • For NodeJS or equivalent, an instance of LocalStorage from "node-localstoarge" NPM module can be used.
  • A custom storage that implements StorageCompact interface can also be used both in browser and NodeJS.

Fallback behavior:

  • undefined: will attempt to use globalThis.localStorage, if available
  • null, will defer storage check until initialization on first read/write or when init() invoked manually.
    • If storage is undefined or null will attempt to assign globalTihs.localStorage again
    • If storage is still falsy, will throw an error.

Default:

  • browser: localStorage
  • node: undefined (in-memory mode)

stringify? ​

optional stringify?: Store_Stringify<Map<Key, Value>, IStore<Key, Value, CacheDisabled>>

Defined in: store/src/types/IStore.ts:261

A callback function to customize the serialization of data before it is written to storage.

This allows you to transform the data Map<Key, Value> into a string format suitable for the underlying storage (e.g., JSON). It serves as the functional inverse of parse.

Use this to sanitize data, remove circular references, or optimize the storage size by only persisting necessary fields.

Fallback Behavior:

  • If this function is not defined, or returns undefined or a non-string value, the system falls back to internal JSON.stringify logic.
  • If the function throws an error, it will use and empty string.

Error Triggers:

Param ​

data

a map of all values stored in this storage

Returns ​

string or undefined

Example ​

Sanitize data before saving ​

javascript
import { Store } from '@superutils/store'

const stringify = (data) => {
  // Convert Map to an array of entries, removing sensitive fields
  const entries = Array.from(data).map(([id, user]) => { // eslint-disable-line @typescript-eslint/no-unused-vars
    const { password, ...publicData } = user
    return [id, publicData]
  })
  return JSON.stringify(entries)
}
const storage = new Store('users', { stringify })

subject$ ​

readonly subject$: CacheDisabled extends true ? Subject<Map<Key, Value>> : BehaviorSubject<Map<Key, Value>>

Defined in: store/src/types/IStore.ts:162

The underlying RxJS subject that serves as the primary reactive interface for observing data modifications.

Its implementation type is determined by the caching strategy:

  • BehaviorSubject: Used when caching is enabled. It maintains the current state and emits it immediately to new subscribers.
  • Subject: Used when caching is disabled. It acts as a pure event pipe, emitting updates only at the moment they occur without retaining an in-memory copy.

toJSON ​

readonly toJSON: Store_ToJSON<Key, Value>

Defined in: store/src/types/IStore.ts:465

Convert list of items (Map) to JSON string of 2D Array


toObject ​

readonly toObject: <T>(data?) => T

Defined in: store/src/types/IStore.ts:468

Convert list of items into an object

Type Parameters ​

T ​

T extends object = Record<PropertyKey & Key, Value>

Parameters ​

data? ​

Map<Key, Value>

Returns ​

T


toString ​

readonly toString: (data?) => string

Defined in: store/src/types/IStore.ts:473

Convert list of items (Map) to JSON string of 2D Array

Parameters ​

data? ​

Map<Key, Value>

Returns ​

string


type ​

readonly type: Store_Type

Defined in: store/src/types/IStore.ts:151

Specifies how the store's data is represented when stored in and parsed from the underlying persistent storage.

  • 'map': Data is serialized as a 2D array (map entries).
  • 'object': Data is serialized as a plain object, with keys and values converted using IStore.toObject.

Default: 'map'


unsubscribe ​

readonly unsubscribe: () => void

Defined in: store/src/types/IStore.ts:483

Unsubscribe from all internal subscriptions.

This will result in:

  • Automatic writing to storage being disabled (manual writes via instance.write() will still work).
  • The onChange callback no longer being triggered.
  • The instance stopping listening to force update cache triggers.

Returns ​

void


validate? ​

optional validate?: Store_ValidatorFactory<IStore<Key, Value, CacheDisabled>, IStore_ValidatorParams<Key, Value>>

Defined in: store/src/types/IStore.ts:539

A configuration object containing optional validation hooks for specific store operations.

This structure allows for granular control over write operations, enabling you to define custom logic to intercept and prevent invalid state updates.

Behavior:

  • Invoked immediately before the store's internal state is updated.
  • If validator throws error, the operation is aborted and the error is propagated to the caller.
  • If validator returns false, the operation is aborted silently.
  • The write validator is invoked during every persistence cycle, serving as a final check after operation-specific hooks (e.g., set or delete).
  • For reference-type values (e.g., Objects, Maps, Arrays), validators can be used to mutate the data (e.g., for normalization) before it is committed.
  • thisArg: all validators are bound to the store instance.

For a list of actions that can be validated, see IStore_ValidatorParams.

Example ​

javascript
import { createObjectStore } from '@superutils/store'

const settingsStore = createObjectStore({
  name: 'app-settings',
  initialValue: {
    theme: 'light',
    version: '1.0.0',
  },
  validate: {
    set([key, value]) {
      console.log(this.size) // "this" refers to the store instance
      if (key !== 'theme' || ['light', 'dark', 'system'].includes(value)) return

      // throw error to abort operation
      throw new Error(`Invalid theme: ${value}`)
    },
    delete: ([keys]) => !keys.includes('version'),
  },
})

settingsStore.set('theme', 'system')
console.log(settingsStore.get('theme')) // 'system'

try {
  settingsStore.set('theme', 'invalid') // throws error
} catch (err) {
  console.error(err.message)
}

// silently ignore
settingsStore.delete('version')

values ​

readonly values: () => Value[]

Defined in: store/src/types/IStore.ts:545

Get all values as an array

Returns ​

Value[]


write ​

readonly write: (data?, silent?) => boolean

Defined in: store/src/types/IStore.ts:558

Write data to the underlying storage (localStorage or file).

Parameters ​

data? ​

Map<Key, Value>

(optional) Data to write.

  • If provided, it overwrites the storage.
  • If not provided, the current in-memory data is used (if cache is enabled).
silent? ​

boolean

(optional) Whether to throw error on failure. Default: true if delay

Returns ​

boolean

true if the write was successful, false otherwise.