or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

canvas.mdcore-framework.mddevice.mddom-query.mdindex.mdlocation.mdmedia.mdnavigation.mdnetwork.mdstorage.mdsystem-info.mdui-interactions.md

storage.mddocs/

0

# Storage APIs

1

2

Complete localStorage-based storage system compatible with Mini Program storage APIs, supporting both synchronous and asynchronous operations with comprehensive data management capabilities.

3

4

## Capabilities

5

6

### Synchronous Storage Operations

7

8

Direct storage operations that execute immediately and return results synchronously.

9

10

```typescript { .api }

11

/**

12

* Store data synchronously in local storage

13

* @param key - Storage key identifier

14

* @param data - Data to store (any JSON-serializable value)

15

*/

16

function setStorageSync(key: string, data: any): void;

17

18

/**

19

* Retrieve data synchronously from local storage

20

* @param key - Storage key identifier

21

* @returns Stored data or empty string if key doesn't exist

22

*/

23

function getStorageSync(key: string): any;

24

25

/**

26

* Remove data synchronously from local storage

27

* @param key - Storage key identifier to remove

28

*/

29

function removeStorageSync(key: string): void;

30

31

/**

32

* Clear all data synchronously from local storage

33

*/

34

function clearStorageSync(): void;

35

36

/**

37

* Get storage information synchronously

38

* @returns Storage statistics and key list

39

*/

40

function getStorageInfoSync(): StorageInfo;

41

```

42

43

**Usage Examples:**

44

45

```typescript

46

import { setStorageSync, getStorageSync, removeStorageSync } from "@tarojs/taro-h5";

47

48

// Store simple data

49

setStorageSync('username', 'alice');

50

setStorageSync('userId', 12345);

51

52

// Store complex objects

53

setStorageSync('user', {

54

id: 1,

55

name: 'Alice',

56

email: 'alice@example.com',

57

preferences: {

58

theme: 'dark',

59

language: 'en'

60

}

61

});

62

63

// Retrieve data

64

const username = getStorageSync('username'); // 'alice'

65

const user = getStorageSync('user'); // Full user object

66

const nonExistent = getStorageSync('missing'); // ''

67

68

// Remove specific items

69

removeStorageSync('userId');

70

71

// Clear all storage

72

clearStorageSync();

73

```

74

75

### Asynchronous Storage Operations

76

77

Promise-based storage operations for non-blocking data management with callback support.

78

79

```typescript { .api }

80

/**

81

* Store data asynchronously in local storage

82

* @param options - Storage options with key and data

83

* @returns Promise that resolves when storage is complete

84

*/

85

function setStorage(options: SetStorageOption): Promise<void>;

86

87

/**

88

* Retrieve data asynchronously from local storage

89

* @param options - Retrieval options with key

90

* @returns Promise that resolves with stored data

91

*/

92

function getStorage<T = any>(options: GetStorageOption): Promise<T>;

93

94

/**

95

* Remove data asynchronously from local storage

96

* @param options - Removal options with key

97

* @returns Promise that resolves when removal is complete

98

*/

99

function removeStorage(options: RemoveStorageOption): Promise<void>;

100

101

/**

102

* Clear all data asynchronously from local storage

103

* @param options - Optional callback options

104

* @returns Promise that resolves when clearing is complete

105

*/

106

function clearStorage(options?: CallbackOptions): Promise<void>;

107

108

/**

109

* Get storage information asynchronously

110

* @param options - Optional callback options

111

* @returns Promise that resolves with storage information

112

*/

113

function getStorageInfo(options?: CallbackOptions): Promise<StorageInfo>;

114

115

interface SetStorageOption extends CallbackOptions {

116

/** Storage key identifier */

117

key: string;

118

/** Data to store (any JSON-serializable value) */

119

data: any;

120

}

121

122

interface GetStorageOption extends CallbackOptions {

123

/** Storage key identifier */

124

key: string;

125

}

126

127

interface RemoveStorageOption extends CallbackOptions {

128

/** Storage key identifier to remove */

129

key: string;

130

}

131

```

132

133

**Usage Examples:**

134

135

```typescript

136

import { setStorage, getStorage, removeStorage, clearStorage } from "@tarojs/taro-h5";

137

138

// Async/await pattern

139

async function handleUserData() {

140

try {

141

// Store user data

142

await setStorage({

143

key: 'currentUser',

144

data: {

145

id: 123,

146

name: 'Bob',

147

lastLogin: new Date().toISOString()

148

}

149

});

150

151

// Retrieve user data

152

const userData = await getStorage<UserData>({

153

key: 'currentUser'

154

});

155

console.log('User:', userData.name);

156

157

// Remove specific data

158

await removeStorage({ key: 'tempData' });

159

160

// Clear all storage

161

await clearStorage();

162

163

} catch (error) {

164

console.error('Storage operation failed:', error);

165

}

166

}

167

168

// Callback pattern

169

setStorage({

170

key: 'settings',

171

data: { theme: 'dark', notifications: true },

172

success: (res) => {

173

console.log('Settings saved successfully');

174

},

175

fail: (error) => {

176

console.error('Failed to save settings:', error);

177

},

178

complete: () => {

179

console.log('Storage operation completed');

180

}

181

});

182

```

183

184

### Storage Information

185

186

Utilities for monitoring storage usage and available keys.

187

188

```typescript { .api }

189

/**

190

* Storage information object containing usage statistics

191

*/

192

interface StorageInfo {

193

/** Array of all storage keys currently in use */

194

keys: string[];

195

/** Current storage size in KB (approximate) */

196

currentSize: number;

197

/** Maximum storage limit in KB (browser dependent) */

198

limitSize: number;

199

}

200

```

201

202

**Usage Examples:**

203

204

```typescript

205

import { getStorageInfoSync, getStorageInfo } from "@tarojs/taro-h5";

206

207

// Synchronous storage info

208

const info = getStorageInfoSync();

209

console.log(`Stored keys: ${info.keys.length}`);

210

console.log(`Current usage: ${info.currentSize}KB / ${info.limitSize}KB`);

211

console.log('Keys:', info.keys);

212

213

// Asynchronous storage info

214

const storageInfo = await getStorageInfo();

215

const usagePercent = (storageInfo.currentSize / storageInfo.limitSize) * 100;

216

console.log(`Storage usage: ${usagePercent.toFixed(1)}%`);

217

218

// Check if specific key exists

219

const hasUserData = info.keys.includes('userData');

220

if (hasUserData) {

221

console.log('User data is stored');

222

}

223

```

224

225

### Error Handling

226

227

Storage operations can fail due to quota limits, invalid data, or browser restrictions.

228

229

```typescript

230

// Handling storage quota exceeded

231

try {

232

setStorageSync('largeData', new Array(1000000).fill('data'));

233

} catch (error) {

234

if (error.message.includes('quota')) {

235

console.log('Storage quota exceeded');

236

// Handle quota error - maybe clear old data

237

const info = getStorageInfoSync();

238

console.log(`Current usage: ${info.currentSize}KB`);

239

}

240

}

241

242

// Async error handling

243

async function safeStorageOperation() {

244

try {

245

await setStorage({

246

key: 'criticalData',

247

data: importantUserData

248

});

249

} catch (error) {

250

// Fallback strategies

251

console.error('Primary storage failed:', error);

252

253

// Try clearing old data and retry

254

await clearStorage();

255

await setStorage({

256

key: 'criticalData',

257

data: importantUserData

258

});

259

}

260

}

261

```

262

263

### Data Type Handling

264

265

Storage automatically serializes and deserializes JSON-compatible data types.

266

267

```typescript

268

// Supported data types

269

setStorageSync('string', 'Hello World');

270

setStorageSync('number', 42);

271

setStorageSync('boolean', true);

272

setStorageSync('array', [1, 2, 3, 'four']);

273

setStorageSync('object', {

274

nested: {

275

property: 'value'

276

},

277

array: [1, 2, 3],

278

date: new Date().toISOString() // Dates as ISO strings

279

});

280

setStorageSync('null', null);

281

282

// Unsupported types (functions, undefined, symbols)

283

// These will be omitted or converted during JSON serialization

284

const complexObject = {

285

validProp: 'This will be stored',

286

func: () => {}, // Will be omitted

287

undef: undefined, // Will be omitted

288

symb: Symbol('test') // Will be omitted

289

};

290

291

setStorageSync('complex', complexObject);

292

const retrieved = getStorageSync('complex');

293

// retrieved = { validProp: 'This will be stored' }

294

```

295

296

### Best Practices

297

298

```typescript

299

// 1. Use descriptive keys with namespacing

300

setStorageSync('user:profile', userProfile);

301

setStorageSync('app:settings', appSettings);

302

setStorageSync('cache:apiData', apiResponse);

303

304

// 2. Handle missing data gracefully

305

function getUserPreferences() {

306

const prefs = getStorageSync('user:preferences');

307

return prefs || {

308

theme: 'light',

309

language: 'en',

310

notifications: true

311

};

312

}

313

314

// 3. Implement data versioning for updates

315

const DATA_VERSION = '1.2.0';

316

317

function saveVersionedData(key: string, data: any) {

318

setStorageSync(key, {

319

version: DATA_VERSION,

320

data: data,

321

timestamp: Date.now()

322

});

323

}

324

325

function loadVersionedData(key: string) {

326

const stored = getStorageSync(key);

327

if (!stored || stored.version !== DATA_VERSION) {

328

// Handle version mismatch or missing data

329

return null;

330

}

331

return stored.data;

332

}

333

334

// 4. Monitor storage usage

335

function checkStorageHealth() {

336

const info = getStorageInfoSync();

337

const usagePercent = (info.currentSize / info.limitSize) * 100;

338

339

if (usagePercent > 80) {

340

console.warn('Storage usage is high:', usagePercent + '%');

341

// Implement cleanup strategy

342

cleanupOldCache();

343

}

344

}

345

346

function cleanupOldCache() {

347

const info = getStorageInfoSync();

348

const cacheKeys = info.keys.filter(key => key.startsWith('cache:'));

349

350

// Remove old cache entries

351

cacheKeys.forEach(key => {

352

const data = getStorageSync(key);

353

if (data.timestamp < Date.now() - (7 * 24 * 60 * 60 * 1000)) { // 7 days old

354

removeStorageSync(key);

355

}

356

});

357

}

358

```

359

360

### Batch Storage Operations (Not Supported)

361

362

Advanced batch operations for handling multiple storage items simultaneously. These APIs are temporarily not supported in the H5 implementation.

363

364

```typescript { .api }

365

/**

366

* Set multiple storage items in a single batch operation

367

* Note: Temporarily not supported - returns success stub

368

* @param options - Batch set storage options

369

* @returns Promise that resolves with success stub

370

*/

371

function batchSetStorage(options: BatchSetStorageOption): Promise<void>;

372

373

/**

374

* Set multiple storage items synchronously in a single batch operation

375

* Note: Temporarily not supported - returns success stub

376

* @param kvList - Array of key-value pairs to store

377

*/

378

function batchSetStorageSync(kvList: KeyValuePair[]): void;

379

380

/**

381

* Get multiple storage items in a single batch operation

382

* Note: Temporarily not supported - returns success stub

383

* @param options - Batch get storage options

384

* @returns Promise that resolves with success stub

385

*/

386

function batchGetStorage(options: BatchGetStorageOption): Promise<BatchGetStorageResult>;

387

388

/**

389

* Get multiple storage items synchronously in a single batch operation

390

* Note: Temporarily not supported - returns empty result

391

* @param keyList - Array of keys to retrieve

392

* @returns Empty result object

393

*/

394

function batchGetStorageSync(keyList: string[]): BatchGetStorageResult;

395

396

interface KeyValuePair {

397

/** Storage key identifier */

398

key: string;

399

/** Data to store */

400

data: any;

401

}

402

403

interface BatchSetStorageOption extends CallbackOptions {

404

/** Array of key-value pairs to store */

405

kvList: KeyValuePair[];

406

}

407

408

interface BatchGetStorageOption extends CallbackOptions {

409

/** Array of keys to retrieve */

410

keyList: string[];

411

}

412

413

interface BatchGetStorageResult {

414

/** Retrieved key-value pairs */

415

kvList: KeyValuePair[];

416

}

417

```

418

419

**Alternative Implementation:**

420

421

Since batch operations are not natively supported, you can implement them using individual storage operations:

422

423

```typescript

424

// Alternative batch set implementation

425

async function customBatchSetStorage(kvList: KeyValuePair[]): Promise<void> {

426

const promises = kvList.map(({ key, data }) =>

427

setStorage({ key, data }).catch(error => ({ key, error }))

428

);

429

430

const results = await Promise.all(promises);

431

const errors = results.filter(result => result && 'error' in result);

432

433

if (errors.length > 0) {

434

console.warn('Some batch set operations failed:', errors);

435

}

436

437

console.log(`Batch set completed: ${kvList.length - errors.length}/${kvList.length} successful`);

438

}

439

440

// Alternative batch get implementation

441

async function customBatchGetStorage(keyList: string[]): Promise<BatchGetStorageResult> {

442

const promises = keyList.map(async (key) => {

443

try {

444

const data = await getStorage({ key });

445

return { key, data };

446

} catch (error) {

447

console.warn(`Failed to get key "${key}":`, error);

448

return null;

449

}

450

});

451

452

const results = await Promise.all(promises);

453

const kvList = results.filter(result => result !== null) as KeyValuePair[];

454

455

return { kvList };

456

}

457

458

// Usage example

459

async function demonstrateBatchOperations() {

460

// Batch set data

461

const dataToSet = [

462

{ key: 'user:profile', data: { name: 'Alice', age: 25 } },

463

{ key: 'user:settings', data: { theme: 'dark', language: 'en' } },

464

{ key: 'app:version', data: '1.2.0' }

465

];

466

467

await customBatchSetStorage(dataToSet);

468

469

// Batch get data

470

const keysToGet = ['user:profile', 'user:settings', 'app:version'];

471

const result = await customBatchGetStorage(keysToGet);

472

473

console.log('Retrieved data:', result.kvList);

474

}

475

```

476

477

### Buffer Storage Operations (Not Supported)

478

479

Buffer URL creation and management for handling binary data. These APIs are temporarily not supported in the H5 implementation.

480

481

```typescript { .api }

482

/**

483

* Create buffer URL for binary data handling

484

* Note: Temporarily not supported - returns stub

485

* @param buffer - Binary data buffer

486

* @returns Placeholder buffer URL

487

*/

488

function createBufferURL(buffer: ArrayBuffer): string;

489

490

/**

491

* Revoke previously created buffer URL

492

* Note: Temporarily not supported - returns stub

493

* @param bufferUrl - Buffer URL to revoke

494

*/

495

function revokeBufferURL(bufferUrl: string): void;

496

```

497

498

**Alternative Implementation:**

499

500

Use standard Web APIs for buffer handling:

501

502

```typescript

503

// Alternative buffer URL implementation using Web APIs

504

function createWebBufferURL(data: ArrayBuffer, mimeType: string = 'application/octet-stream'): string {

505

const blob = new Blob([data], { type: mimeType });

506

return URL.createObjectURL(blob);

507

}

508

509

function revokeWebBufferURL(bufferUrl: string): void {

510

URL.revokeObjectURL(bufferUrl);

511

}

512

513

// Usage example

514

function handleBinaryData(arrayBuffer: ArrayBuffer) {

515

// Create buffer URL

516

const bufferUrl = createWebBufferURL(arrayBuffer, 'image/jpeg');

517

518

// Use the buffer URL (e.g., display image)

519

const img = document.createElement('img');

520

img.src = bufferUrl;

521

document.body.appendChild(img);

522

523

// Clean up when done

524

img.onload = () => {

525

setTimeout(() => {

526

revokeWebBufferURL(bufferUrl);

527

}, 1000);

528

};

529

}

530

```

531

532

## Types

533

534

```typescript { .api }

535

interface CallbackOptions {

536

/** Success callback function */

537

success?: (res: any) => void;

538

/** Failure callback function */

539

fail?: (err: any) => void;

540

/** Completion callback function (called regardless of success/failure) */

541

complete?: (res: any) => void;

542

}

543

544

interface UserData {

545

id: number;

546

name: string;

547

email?: string;

548

lastLogin: string;

549

preferences?: {

550

theme: 'light' | 'dark';

551

language: string;

552

notifications: boolean;

553

};

554

}

555

```