StringStorage is a TypeScript-based library that simplifies working with Web Storage (localStorage and sessionStorage), providing automatic handling of data persistence with expiration, seamless integration with HTML form elements, and support for complex data structures. It's crafted to enhance user experience by persisting form inputs and application states across sessions with minimal setup.
- Automatic Persistence: Effortlessly saves and restores form inputs and application state across page reloads and sessions.
- Expiration Support: Allows setting expiration times for stored data, automatically removing expired data.
- Easy Integration: Works out of the box with form elements for saving and restoring their values without additional coding.
- Complex Data Handling: Supports saving not just string values but also complex data structures in a JSON-compatible format.
- Session and Local Storage Management: Provides a unified API to interact with both localStorage and sessionStorage, simplifying their use.
npm install @fiddle-digital/string-storage
import StringStorage from '@fiddle-digital/string-storage';
To start using StringStorage:
const storage = StringStorage.getInstance();
StringStorage can automatically save and restore the values of form elements. Simply add the data-string-storage attribute to your form:
<form data-string-storage>
<input type="text" data-string-id="username" />
<textarea data-string-id="bio"></textarea>
<select data-string-id="country">
<option value="us">United States</option>
<option value="ca">Canada</option>
</select>
<button type="submit">Submit</button>
</form>
To save data to localStorage:
storage.local.set('key', 'value', {days: 1});
To save data to sessionStorage:
storage.session.set('key', 'value');
To retrieve data from localStorage:
const value = storage.local.get('key', 'default');
const exists = storage.local.has('key');
To remove data from localStorage:
storage.local.delete('key');
StringStorage allows setting expiration for stored data, which is automatically respected and cleaned up:
storage.local.set('temporary', 'data', {hours: 1});
After 1 hour, temporary will be automatically removed from storage.