# misc/localstorage (vanilla.js 0.4.0)

> https://vanillapunch.com/docs/vanilla.js/0.4.0/api/misc/localstorage/

Local storage.

## LocalStorage extends Object

Local storage.
- The default storage is the browser's window.localStorage. setBackend can swap in another storage (such as a platform SDK's storage).
- Wraps every access in try. If the storage is blocked (private window, blocked cookies) or full and unusable, it throws no exception and
  keeps the value in memory instead while this page is alive. (that value is gone after a restart, isMemoryFallback)
- Reads (getString, getBoolean, getNumber, getJson) do not write the default value for missing keys.

Example: Save and read a score and settings

```js
import { LocalStorage } from "./build/vanilla.js";

LocalStorage.setNumber("example.bestScore", 1200);
LocalStorage.setBoolean("example.isMuted", true);
LocalStorage.setJson("example.settings", { volume: 0.8, language: "en" });
const bestScore = LocalStorage.getNumber("example.bestScore", 0);
const isMuted = LocalStorage.getBoolean("example.isMuted", false);
const settings = LocalStorage.getJson("example.settings", {});
console.log(bestScore, isMuted, settings.volume, LocalStorage.containsKey("example.bestScore"));
const removedCount = LocalStorage.clearByPrefix("example.");
console.log(removedCount, LocalStorage.isMemoryFallback());
```

- `constructor()` (constructor, since 0.1.0): Constructor.
- `static setBackend(backend)` (static, since 0.4.0): Swaps the storage. (null returns to the browser window.localStorage)
  - backend is an object with getItem(key) → string | null, setItem(key, value), removeItem(key). (same shape as Storage)
  - To use the key list (getKeys, clearByPrefix) and full removal (clear), also provide getKeys() → string[], and clear() to delete everything at once.
  - Swapping discards the values kept in memory instead.
  - `backend` { getItem: Function, setItem: Function, removeItem: Function, getKeys?: Function, clear?: Function } | null: Storage to swap in. (window.localStorage if null or undefined)

  Example: Swap in your own storage

  ```js
  import { LocalStorage } from "./build/vanilla.js";
  
  const itemMap = new Map();
  LocalStorage.setBackend({
  	getItem: (key) => {
  		return itemMap.has(key) ? itemMap.get(key) : null;
  	},
  	setItem: (key, value) => {
  		itemMap.set(key, value);
  	},
  	removeItem: (key) => {
  		itemMap.delete(key);
  	},
  	getKeys: () => {
  		return Array.from(itemMap.keys());
  	}
  });
  LocalStorage.setString("profile.name", "Player");
  console.log(itemMap.get("profile.name"), LocalStorage.getKeys());
  LocalStorage.setBackend(null);
  ```

- `static getBackend()` (static, since 0.4.0): Returns the swapped-in storage. (null if none)
  - returns object | null: The swapped-in storage. null if none.
- `static setStorageDirectory(storageDirectoryPath)` (static, since 0.4.0): Sets the save folder directly. (the folder where the Rust version on desktop keeps localstorage.json, this version does nothing because the browser decides it per page address)
  - Kept so the same game code runs on both engines. The Rust version on the web does nothing either.
  - `storageDirectoryPath` string | null: Folder to keep localstorage.json in. (null means the default folder chosen from the app name)

  Example: Saving still goes to the browser storage even with a save folder set

  ```js
  import { LocalStorage } from "./build/vanilla.js";
  
  LocalStorage.setStorageDirectory("saves");
  LocalStorage.setString("profile.name", "Player");
  console.log(LocalStorage.getString("profile.name"));
  ```

- `static isMemoryFallback()` (static, since 0.4.0): Whether it has ever fallen back to memory because the storage was unusable.
  - returns boolean: True if memory has ever been used instead. (returns to false when setBackend is called)
- `static getItem(key)` (static, since 0.4.0): Reads one value. (null if missing, values kept in memory instead take precedence)
  - `key` string: Key.
  - returns string | null: The stored text. null if missing or unreadable.
- `static setItem(key, value)` (static, since 0.4.0): Writes one value. (true if written to the storage, false if it could not and was kept in memory instead)
  - `key` string: Key.
  - `value` string: Text to write.
  - returns boolean: True if written to the storage. False if kept in memory instead.
- `static removeItem(key)` (static, since 0.4.0): Removes one value. (also removes the value kept in memory instead)
  - `key` string: Key to remove.
- `static clear()` (static, since 0.1.0): Removes all.
- `static setString(key, stringValue)` (static, since 0.1.0): Sets a string value.
  - `key` string: Key.
  - `stringValue` string: Text to write.
- `static setBoolean(key, booleanValue)` (static, since 0.1.0): Sets a boolean value.
  - `key` string: Key.
  - `booleanValue` boolean: Value to write. (written as the text "true" or "false")
- `static setNumber(key, numberValue)` (static, since 0.1.0): Sets a number value.
  - `key` string: Key.
  - `numberValue` number: Value to write. (converted with String)
- `static remove(key)` (static, since 0.1.0): Removes a value.
  - `key` string: Key to remove.
- `static getString(key, defaultStringValue = "")` (static, since 0.1.0): Returns a string value. (default value if missing, not written to the storage)
  - `key` string: Key.
  - `defaultStringValue` string: Value returned when missing.
  - returns string: The stored text. The default value if missing.
- `static getBoolean(key, defaultBooleanValue = false)` (static, since 0.1.0): Returns a boolean value.
  - `key` string: Key.
  - `defaultBooleanValue` boolean: Value returned when missing or empty.
  - returns boolean: True if the stored text is "true". The default value if missing or empty.
- `static getNumber(key, defaultNumberValue = 0)` (static, since 0.1.0): Returns a number value.
  - `key` string: Key.
  - `defaultNumberValue` number: Value returned when missing or empty.
  - returns number: The stored text converted with Number. (the default value if missing or empty, NaN if not a number)
- `static clearByPrefix(prefix)` (static, since 0.3.0): Deletes all keys starting with the prefix at once. (static)
  - Used to wipe a game namespace's saved data entirely.
  - `prefix` string: Prefix of the keys to remove. (removes nothing if empty)
  - returns number: Number of removed keys.
- `static containsKey(key)` (static, since 0.1.0): Returns whether the key exists. (also checks values kept in memory instead)
  - `key` string: Key to look for.
  - returns boolean: True if a value exists.
- `static getKeys()` (static, since 0.1.0): Returns all keys.
  - returns string[]: Sorted array of the keys in the storage and in memory combined.
- `static getJson(key, defaultValue = null)` (static, since 0.4.0): Returns a JSON value. (default value if missing or unparsable, not written to the storage)
  - `key` string: Key.
  - `defaultValue` any: Value returned when missing, empty or unparsable.
  - returns any: The parsed value. The default value if missing or unparsable.
- `static setJson(key, value)` (static, since 0.4.0): Sets a JSON value. (converts to JSON text and writes it. If the value cannot be converted (circular references, etc.), does not write and returns false)
  - `key` string: Key.
  - `value` any: Value to write as JSON.
  - returns boolean: Whether it was written to the storage. (false if kept in memory instead or not convertible)
