@friendofsvelte/state 0.0.1-dev → 0.0.2

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.
@@ -11,6 +11,7 @@ type GetTypeFromRegistry<K extends keyof PodTypeRegistry> = PodTypeRegistry[K] e
11
11
  * @param key - The key to store the state.
12
12
  * @param storage - The storage type to use.
13
13
  * @param context - The initial state or override.
14
+ * @param override - Whether to override the stored value with the provided context.
14
15
  */
15
- export declare function pod<K extends keyof PodTypeRegistry>(key: K, storage?: StorageType, context?: GetTypeFromRegistry<K>): GetTypeFromRegistry<K>;
16
+ export declare function pod<K extends keyof PodTypeRegistry>(key: K, storage?: StorageType, context?: GetTypeFromRegistry<K>, override?: boolean): GetTypeFromRegistry<K>;
16
17
  export {};
@@ -1,17 +1,20 @@
1
1
  import { untrack } from 'svelte';
2
- function track(key, storage, context) {
2
+ function track(key, storage, context, override = false) {
3
3
  let state = $state(context ?? {});
4
4
  if (typeof window !== 'undefined') {
5
- if (context === undefined) {
6
- const storedValue = untrack(() => window[storage].getItem(String(key)));
7
- if (storedValue) {
8
- try {
9
- state = JSON.parse(storedValue);
10
- }
11
- catch {
12
- state = {};
13
- }
5
+ const storedValue = untrack(() => window[storage].getItem(String(key)));
6
+ if (storedValue && !override) {
7
+ try {
8
+ state = JSON.parse(storedValue);
14
9
  }
10
+ catch {
11
+ state = {};
12
+ }
13
+ }
14
+ else if (override || !storedValue) {
15
+ state = context ?? {};
16
+ const json = JSON.stringify($state.snapshot(state));
17
+ window[storage].setItem(String(key), json);
15
18
  }
16
19
  $effect.pre(() => {
17
20
  const json = JSON.stringify($state.snapshot(state));
@@ -25,7 +28,8 @@ function track(key, storage, context) {
25
28
  * @param key - The key to store the state.
26
29
  * @param storage - The storage type to use.
27
30
  * @param context - The initial state or override.
31
+ * @param override - Whether to override the stored value with the provided context.
28
32
  */
29
- export function pod(key, storage = 'localStorage', context) {
30
- return track(key, storage, context);
33
+ export function pod(key, storage = 'localStorage', context, override = false) {
34
+ return track(key, storage, context, override);
31
35
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@friendofsvelte/state",
3
- "version": "0.0.1-dev",
3
+ "version": "0.0.2",
4
4
  "scripts": {
5
5
  "dev": "vite dev",
6
6
  "build": "vite build && npm run prepack",