apphouse
Version:
Component library for React that uses observable state management and theme-able components.
56 lines (49 loc) • 1.22 kB
text/typescript
import { makeAutoObservable } from 'mobx';
/**
* Class representing a local storage instance.
* @class
*/
export class LocalStorage {
/**
* Storage instance.
* @type {Storage}
*/
db: Storage;
/**
* Constructs a new LocalStorage instance.
* @constructor
*/
constructor() {
this.db = window.localStorage;
makeAutoObservable(this);
}
/**
* Sets a value in the local storage.
* @param {string} id - The id/key of the value to set.
* @param {any} data - The data value to set.
*/
set(id: string, data: unknown) {
const value = JSON.stringify(data);
this.db.setItem(id, value);
}
/**
* Retrieves a value from the local storage.
* @param {string} id - The id/key of the value to retrieve.
* @returns {string | undefined} - The retrieved value.
*/
get(id: string): string | undefined {
return this.db.getItem(id) || undefined;
}
/**
* Removes a value from the local storage.
* @param {string} id - The id/key of the value to remove.
*/
remove(id: string) {
this.db.removeItem(id);
}
}
/**
* Default instance of the LocalStorage class.
* @type {LocalStorage}
*/
export const localStorage = new LocalStorage();