@leexi/shared 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ export { useLocalStorage } from './useLocalStorage';
@@ -0,0 +1 @@
1
+ export { useLocalStorage } from './useLocalStorage';
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Creates a reactive pointer to a specific localStorage value.
3
+ * The value is stored in the localStorage as a JSON stringified data to enable parsing primitives and objects
4
+ *
5
+ * @param key - a key pointing to a localStorage value
6
+ * @param defaultValue - an optional default value used if the localStorage value is undefined
7
+ * @returns a reactive variable pointing to that localStorage value
8
+ *
9
+ * @example
10
+ * const fooOne = useLocalStorage('foo')
11
+ * const fooTwo = useLocalStorage('foo', 'bar')
12
+ * fooOne.value // => 'bar'
13
+ * localStorage.foo // => '"bar"'
14
+ */
15
+ export declare const useLocalStorage: <T>(key: string, defaultValue?: T) => any;
@@ -0,0 +1,27 @@
1
+ import { useState, watch } from '#imports';
2
+ /**
3
+ * Creates a reactive pointer to a specific localStorage value.
4
+ * The value is stored in the localStorage as a JSON stringified data to enable parsing primitives and objects
5
+ *
6
+ * @param key - a key pointing to a localStorage value
7
+ * @param defaultValue - an optional default value used if the localStorage value is undefined
8
+ * @returns a reactive variable pointing to that localStorage value
9
+ *
10
+ * @example
11
+ * const fooOne = useLocalStorage('foo')
12
+ * const fooTwo = useLocalStorage('foo', 'bar')
13
+ * fooOne.value // => 'bar'
14
+ * localStorage.foo // => '"bar"'
15
+ */
16
+ export const useLocalStorage = (key, defaultValue) => {
17
+ const data = useState(key, () => JSON.parse(localStorage?.getItem(key) || 'null') || defaultValue);
18
+ watch(data, () => {
19
+ if (data.value) {
20
+ localStorage?.setItem(key, JSON.stringify(data.value));
21
+ }
22
+ else {
23
+ localStorage?.removeItem(key);
24
+ }
25
+ }, { immediate: true });
26
+ return data;
27
+ };