feat(local-storage): add clearItem, clearAll instance methods

This commit is contained in:
Eric Y Liu 2021-07-09 11:57:11 -07:00
commit 6c478b8193
7 changed files with 111 additions and 8 deletions

View file

@ -5351,6 +5351,26 @@
"isFunction": false,
"constant": false,
"reactive": true
},
{
"name": "clearItem",
"kind": "function",
"description": "Remove the persisted key value from the browser's local storage",
"type": "() => void",
"value": "() => { localStorage.removeItem(key); }",
"isFunction": true,
"constant": false,
"reactive": false
},
{
"name": "clearAll",
"kind": "function",
"description": "Clear all key values from the browser's local storage",
"type": "() => void",
"value": "() => { localStorage.clear(); }",
"isFunction": true,
"constant": false,
"reactive": false
}
],
"slots": [],

View file

@ -5,5 +5,17 @@
This utility component wraps the [Window.localStorage API](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) and is useful for persisting ephemeral data (e.g., color theme) at the browser level.
### Reactive example
In the example below, toggle the switch and reload the page. The updated theme should be persisted locally.
<FileSource src="/framed/LocalStorage/LocalStorage" />
<FileSource src="/framed/LocalStorage/LocalStorage" />
### Clear item, clear all
Use the `bind:this` directive to access the `clearItem` and `clearAll` methods.
Invoking `clearItem` will remove the persisted key value from the browser's local storage.
Invoking `clearAll` will remove all key values.
<FileSource src="/framed/LocalStorage/LocalStorageClear" />

View file

@ -1,7 +1,6 @@
<script>
import { LocalStorage, Toggle, Button } from "carbon-components-svelte";
import { LocalStorage, Toggle } from "carbon-components-svelte";
let storage;
let toggled = false;
let events = [];
@ -9,7 +8,6 @@
</script>
<LocalStorage
bind:this="{storage}"
key="dark-mode"
bind:value="{toggled}"
on:save="{() => {

View file

@ -0,0 +1,43 @@
<script>
import { LocalStorage, Toggle, Button } from "carbon-components-svelte";
let storage;
let toggled = false;
let events = [];
$: document.documentElement.setAttribute("theme", toggled ? "g100" : "white");
</script>
<LocalStorage
bind:this="{storage}"
key="dark-mode"
bind:value="{toggled}"
on:save="{() => {
events = [...events, { event: 'on:save' }];
}}"
on:update="{({ detail }) => {
events = [...events, { event: 'on:update', detail }];
}}"
/>
<Toggle size="sm" labelText="Dark mode" bind:toggled />
<br />
<br />
<Button
size="small"
on:click="{() => {
events = [];
storage.clearAll();
}}"
>
Clear local storage
</Button>
<br />
<br />
<pre>
{JSON.stringify(events, null, 2)}
</pre>