Skip to content

Local Storage

Brandon Jordan edited this page Aug 20, 2025 · 18 revisions

Manage Local Storage Item

Spark provides a class for using a local storage value while keeping the value type intact. It also allows for a default value and provides useful methods like size() and empty().

Example:

// Create local storage value object.
const firstLaunch = new LocalStorageValue(key: 'firstLaunch', defaultValue: true);

firstLaunch.get(); // Get local storage value or default value if empty.

firstLaunch.set(newValue); // Sets it to new value and preserves value type.

firstLaunch.clear(); // Sets key value to null.

firstLaunch.remove(); // Deletes the local storage item for the key.

firstLaunch.empty(); // Checks if the raw value of the local storage item is empty.

firstLaunch.size(); // Gets the size of the local storage value.

firstLaunch.value(); // Get local storage value with no default value.

Keep in mind, the local storage item is managed by Spark. It preserves the type of the value by putting the value in an object and stringifying it into a JSON value. When using get(), the JSON value of the local storage item is parsed and the value is returned with its type preserved.

Local Storage Store

Spark also provides a Store for modeling local storage items. It uses a LocalStorageValue object to get and set the value of the local storage item. Methods remove() and clear() are passed through.

new LocalStorageStore(key, defaultValue);

Cache

This is similar to a Laravel concept, but not a singleton. Create an instance of Cache to cache a value in local storage:

const feedCache = new Cache('rss-feed', async () => {
    return await fetch('/articles').then(r => r.text())
});

await feedCache.size()
await feedCache.empty()

// Flush the cached value
feedCache.forget()

It's made for async functions.

// This will either return a promise or the value directly from local storage.
const feedXML = await feedCache.get();

Just like the other local storage classes, it's compatible with all types of values and keeps value types intact by enclosing the value in an object (if it's not an object value), then later using that value if it detects it.

Clone this wiki locally