clearLocalStorage
Clears all data from localStorage.
1/**
2 * Clears all data from localStorage.
3 */
4export function clearLocalStorage(): void {
5 try {
6 localStorage.clear();
7 } catch (e) {
8 console.error('Failed to clear localStorage:', e);
9 }
10}
Full Storage Reset
Provides a quick and efficient way to clear all key-value pairs from localStorage in a single call.
Error-Resilient
Wrapped in a
try-catch
block to prevent runtime failures in restricted environments (e.g. incognito mode, quota exceeded).Simplifies Debugging and Testing
Useful for resetting local state between test runs or during development.
Consistent Logging
Reports failures clearly through
console.error
, aiding visibility during troubleshooting.
Tests | Examples
1beforeEach(() => {
2 localStorage.clear();
3 jest.clearAllMocks();
4});
5
6test('clearLocalStorage - removes all keys', () => {
7 localStorage.setItem('a', '1');
8 localStorage.setItem('b', '2');
9 clearLocalStorage();
10 expect(localStorage.length).toBe(0);
11});
12
13test('clearLocalStorage - logs error on failure', () => {
14 const spy = jest.spyOn(console, 'error').mockImplementation(() => {});
15 const originalClear = localStorage.clear;
16 Object.defineProperty(localStorage, 'clear', {
17 value: () => { throw new Error('Failure'); }
18 });
19
20 clearLocalStorage();
21 expect(console.error).toHaveBeenCalled();
22
23 // Restore original method
24 Object.defineProperty(localStorage, 'clear', {
25 value: originalClear
26 });
27});
Common Use Cases
User Logout or Account Deletion
Clear all stored data tied to a user session when logging out or removing a profile.
Environment Resets in Testing Tools
Reset application state during automated testing or manual QA.
Settings or Preferences Reset
Provide a “Reset to Defaults” feature that removes all localStorage-based user preferences.
Data Clearance During App Version Migration
Remove potentially incompatible cached data during major app updates.