Skip to content

Storage

The Storage Component provides a convenient wrapper for working with browser’s localStorage and sessionStorage. It allows you to store, retrieve, and manage data with namespaced keys.

The Storage Component accepts the following parameter when initialized:

ParameterTypeDefaultDescription
typeStoragelocalStorageThe storage type to use (localStorage or sessionStorage)

A pre-configured instance that uses localStorage.

A pre-configured instance that uses sessionStorage.

Sets the namespace key prefix for all storage operations.

Metro.storage.setKey("myApp");

Returns the current namespace key prefix.

const currentKey = Metro.storage.getKey();

Stores a value with the specified key. The value is automatically stringified using JSON.

Metro.storage.setItem("settings", { theme: "dark", fontSize: 16 });

Retrieves a value by key. If the key doesn’t exist, returns the default_value.

ParameterTypeDescription
keyStringThe key to retrieve
default_valueAnyValue to return if the key doesn’t exist
reviverFunctionOptional function for transforming the parsed value
const settings = Metro.storage.getItem("settings", { theme: "light" });

getItemPart(key, sub_key, default_value, reviver)

Section titled “getItemPart(key, sub_key, default_value, reviver)”

Retrieves a nested property from a stored object.

ParameterTypeDescription
keyStringThe key to retrieve
sub_keyStringPath to the nested property, using ”->” as separator
default_valueAnyValue to return if the key doesn’t exist
reviverFunctionOptional function for transforming the parsed value
// If settings contains { theme: { mode: "dark", color: "blue" } }
const themeMode = Metro.storage.getItemPart("settings", "theme->mode", "light");

Removes an item from storage.

Metro.storage.delItem("settings");

Returns the approximate size of the storage in the specified unit.

ParameterTypeDescription
unitStringUnit for the size: “b” (bytes), “k” (kilobytes), or “m” (megabytes)
const sizeInKB = Metro.storage.size("k");

This component is a JavaScript utility and does not have CSS variables for styling.

// Set namespace
Metro.storage.setKey("myApplication");
// Store data
Metro.storage.setItem("userPreferences", {
theme: "dark",
fontSize: 16,
notifications: true
});
// Retrieve data
const preferences = Metro.storage.getItem("userPreferences", {});
// Get a specific property
const theme = Metro.storage.getItemPart("userPreferences", "theme", "light");
// Delete data
Metro.storage.delItem("userPreferences");
// Use session storage
Metro.session.setKey("myApplication");
Metro.session.setItem("temporaryData", { id: 123 });