or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

components.mdcontext.mddevice.mdframework.mdindex.mdlocation.mdmedia.mdnavigation.mdnetwork.mdstorage.mdui-controls.md
tile.json

storage.mddocs/

Storage Operations

Local storage APIs for persistent data management with both synchronous and asynchronous operations supporting various data types including strings, objects, arrays, and primitive values.

Capabilities

Get Storage

Retrieve data from local storage with support for different data types.

/**
 * Get storage data asynchronously
 * @param options - Get storage options
 */
function getStorage(options: GetStorageOptions): Promise<GetStorageResult>;

/**
 * Get storage data synchronously
 * @param key - Storage key
 * @returns Stored data or undefined if not found
 */
function getStorageSync(key: string): any;

interface GetStorageOptions {
  /** Storage key */
  key: string;
  /** Success callback */
  success?: (result: GetStorageResult) => void;
  /** Failure callback */
  fail?: (error: any) => void;
  /** Completion callback */
  complete?: () => void;
}

interface GetStorageResult {
  /** Retrieved data */
  data: any;
}

Usage Examples:

import { getStorage, getStorageSync } from "@dcloudio/uni-h5";

// Async get storage
const result = await getStorage({ key: 'userInfo' });
console.log('User info:', result.data);

// With callback
getStorage({
  key: 'settings',
  success(result) {
    console.log('Settings:', result.data);
  },
  fail(error) {
    console.error('Failed to get settings:', error);
  }
});

// Sync get storage
const token = getStorageSync('authToken');
if (token) {
  // Use token for API requests
  console.log('Auth token found:', token);
}

// Handle different data types
const userPrefs = getStorageSync('userPreferences');
if (userPrefs && typeof userPrefs === 'object') {
  // Handle object data
  console.log('Theme:', userPrefs.theme);
}

Set Storage

Store data in local storage with automatic serialization for complex data types.

/**
 * Set storage data asynchronously
 * @param options - Set storage options
 */
function setStorage(options: SetStorageOptions): Promise<void>;

/**
 * Set storage data synchronously
 * @param key - Storage key
 * @param data - Data to store
 */
function setStorageSync(key: string, data: any): void;

interface SetStorageOptions {
  /** Storage key */
  key: string;
  /** Data to store */
  data: any;
  /** Success callback */
  success?: () => void;
  /** Failure callback */
  fail?: (error: any) => void;
  /** Completion callback */
  complete?: () => void;
}

Usage Examples:

import { setStorage, setStorageSync } from "@dcloudio/uni-h5";

// Store user information
await setStorage({
  key: 'userInfo',
  data: {
    id: 123,
    name: 'John Doe',
    email: 'john@example.com',
    preferences: {
      theme: 'dark',
      language: 'en'
    }
  }
});

// Store with callback
setStorage({
  key: 'appSettings',
  data: { notifications: true, autoSync: false },
  success() {
    console.log('Settings saved successfully');
  },
  fail(error) {
    console.error('Failed to save settings:', error);
  }
});

// Sync storage operations
setStorageSync('authToken', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...');
setStorageSync('lastLoginTime', Date.now());

// Store different data types
setStorageSync('isFirstTime', true); // Boolean
setStorageSync('favoriteItems', [1, 2, 3, 4]); // Array
setStorageSync('score', 85.5); // Number

Remove Storage

Remove specific items from local storage.

/**
 * Remove storage data asynchronously
 * @param options - Remove storage options
 */
function removeStorage(options: RemoveStorageOptions): Promise<void>;

/**
 * Remove storage data synchronously
 * @param key - Storage key to remove
 */
function removeStorageSync(key: string): void;

interface RemoveStorageOptions {
  /** Storage key to remove */
  key: string;
  /** Success callback */
  success?: () => void;
  /** Failure callback */
  fail?: (error: any) => void;
  /** Completion callback */
  complete?: () => void;
}

Usage Examples:

import { removeStorage, removeStorageSync } from "@dcloudio/uni-h5";

// Remove user data on logout
await removeStorage({ key: 'authToken' });
await removeStorage({ key: 'userInfo' });

// Remove with callback
removeStorage({
  key: 'tempData',
  success() {
    console.log('Temporary data cleared');
  }
});

// Sync removal
removeStorageSync('cachedResults');
removeStorageSync('expiredToken');

Clear Storage

Clear all data from local storage.

/**
 * Clear all storage data asynchronously
 * @param options - Clear storage options
 */
function clearStorage(options?: ClearStorageOptions): Promise<void>;

/**
 * Clear all storage data synchronously
 */
function clearStorageSync(): void;

interface ClearStorageOptions {
  /** Success callback */
  success?: () => void;
  /** Failure callback */
  fail?: (error: any) => void;
  /** Completion callback */
  complete?: () => void;
}

Usage Examples:

import { clearStorage, clearStorageSync } from "@dcloudio/uni-h5";

// Clear all data with confirmation
uni.showModal({
  title: 'Clear All Data',
  content: 'This will remove all stored data. Continue?',
  success(result) {
    if (result.confirm) {
      clearStorage({
        success() {
          uni.showToast({
            title: 'All data cleared',
            icon: 'success'
          });
        }
      });
    }
  }
});

// Sync clear (use with caution)
clearStorageSync();

Storage Information

Get information about storage usage and available space.

/**
 * Get storage information asynchronously
 * @param options - Storage info options
 */
function getStorageInfo(options?: GetStorageInfoOptions): Promise<GetStorageInfoResult>;

/**
 * Get storage information synchronously
 * @returns Storage information
 */
function getStorageInfoSync(): GetStorageInfoResult;

interface GetStorageInfoOptions {
  /** Success callback */
  success?: (result: GetStorageInfoResult) => void;
  /** Failure callback */
  fail?: (error: any) => void;
  /** Completion callback */
  complete?: () => void;
}

interface GetStorageInfoResult {
  /** Array of all storage keys */
  keys: string[];
  /** Current storage size in KB */
  currentSize: number;
  /** Maximum storage size in KB */
  limitSize: number;
}

Usage Examples:

import { getStorageInfo, getStorageInfoSync } from "@dcloudio/uni-h5";

// Check storage usage
const storageInfo = await getStorageInfo();
console.log(`Storage usage: ${storageInfo.currentSize}KB / ${storageInfo.limitSize}KB`);
console.log('Stored keys:', storageInfo.keys);

// Check if storage is nearly full
if (storageInfo.currentSize / storageInfo.limitSize > 0.8) {
  uni.showModal({
    title: 'Storage Warning',
    content: 'Storage is nearly full. Consider clearing old data.',
    showCancel: false
  });
}

// Sync storage info
const syncStorageInfo = getStorageInfoSync();
const usagePercent = (syncStorageInfo.currentSize / syncStorageInfo.limitSize) * 100;
console.log(`Storage usage: ${usagePercent.toFixed(1)}%`);

Advanced Storage Patterns

Common patterns for complex storage operations and data management.

Usage Examples:

import { getStorageSync, setStorageSync, removeStorageSync } from "@dcloudio/uni-h5";

// Storage utility class
class StorageManager {
  // Set with expiration
  static setWithExpiry(key: string, data: any, ttl: number) {
    const now = new Date().getTime();
    const item = {
      data: data,
      expiry: now + ttl
    };
    setStorageSync(key, item);
  }
  
  // Get with expiration check
  static getWithExpiry(key: string) {
    const item = getStorageSync(key);
    if (!item) return null;
    
    const now = new Date().getTime();
    if (now > item.expiry) {
      removeStorageSync(key);
      return null;
    }
    return item.data;
  }
  
  // Cache with automatic cleanup
  static setCache(key: string, data: any, maxAge = 300000) { // 5 minutes default
    this.setWithExpiry(`cache_${key}`, data, maxAge);
  }
  
  static getCache(key: string) {
    return this.getWithExpiry(`cache_${key}`);
  }
  
  // Bulk operations
  static setBulk(items: Record<string, any>) {
    Object.entries(items).forEach(([key, value]) => {
      setStorageSync(key, value);
    });
  }
  
  static getBulk(keys: string[]) {
    const result: Record<string, any> = {};
    keys.forEach(key => {
      result[key] = getStorageSync(key);
    });
    return result;
  }
  
  // JSON storage with error handling
  static setJSON(key: string, data: any) {
    try {
      setStorageSync(key, data);
      return true;
    } catch (error) {
      console.error('Failed to store JSON:', error);
      return false;
    }
  }
  
  static getJSON(key: string, defaultValue = null) {
    try {
      const data = getStorageSync(key);
      return data !== undefined ? data : defaultValue;
    } catch (error) {
      console.error('Failed to retrieve JSON:', error);
      return defaultValue;
    }
  }
}

// Usage examples
StorageManager.setWithExpiry('tempToken', 'abc123', 3600000); // 1 hour
const token = StorageManager.getWithExpiry('tempToken');

StorageManager.setCache('apiResponse', responseData);
const cachedData = StorageManager.getCache('apiResponse');

StorageManager.setBulk({
  'setting1': true,
  'setting2': 'value',
  'setting3': { nested: 'object' }
});

const settings = StorageManager.getBulk(['setting1', 'setting2', 'setting3']);

Storage Types

// Storage error types
interface StorageError {
  errMsg: string;
  errCode?: number;
}

// Storage quota information
interface StorageQuota {
  /** Used storage in bytes */
  usage: number;
  /** Total available storage in bytes */
  quota: number;
}

// Storage event types for storage changes
interface StorageChangeEvent {
  /** Changed key */
  key: string;
  /** New value */
  newValue: any;
  /** Previous value */
  oldValue: any;
  /** Storage area */
  storageArea: 'local';
}