Storage

View source

Provides origin-scoped JSON storage as a world resource.

StoragePlugin installs a fresh Storage resource. Values are written to the browser’s localStorage, so they normally survive page reloads and browser sessions until they are removed or the browser clears them. Each value is serialized with JSON.stringify by Storage#set and deserialized with JSON.parse by Storage#get. This resource does not namespace its keys, so its storage area is shared with other code using the same origin’s localStorage.

Examples

import { Storage } from '@wimaengine/storage'

const storage = world.getResource(Storage)
storage.set('settings', { sound: true })
const settings = storage.get('settings')
storage.clear()

Constructor


constructor()

Methods


set(k: string, v: any): void

View source

Serializes v and stores it under k in the origin’s localStorage.

The browser storage API stores strings, so only JSON-serializable values reliably round-trip through this method. JSON.stringify can throw for values such as circular objects or BigInt; standalone undefined, functions, and symbols do not produce JSON that Storage#get can parse.

Parameters

NameDescriptionDefault
k

Storage key.

—
v

JSON-serializable value to store.

—

get<T>(k: string): T

View source

Reads and parses the value stored under k.

Returns undefined when localStorage.getItem(k) returns a falsy value, including when the key is absent. Otherwise, returns the result of JSON.parse; malformed stored JSON therefore throws the parser’s error.

Type Parameters

T

Parameters

NameDescriptionDefault
k

Storage key to retrieve.

—

Returns

The parsed value, or undefined when no value is stored.

clear(): void

View source

Removes every key from the origin’s localStorage.

This clears the browser storage area shared by the current origin, not only values written through this Storage instance.