@plq/use-persisted-state 1.4.1 → 1.4.3

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.
Files changed (64) hide show
  1. package/README.md +3 -3
  2. package/lib/create-async-persisted-state.d.ts.map +1 -1
  3. package/lib/create-async-persisted-state.js +14 -89
  4. package/lib/create-async-persisted-state.js.map +1 -1
  5. package/lib/create-persisted-state.d.ts.map +1 -1
  6. package/lib/create-persisted-state.js +6 -53
  7. package/lib/create-persisted-state.js.map +1 -1
  8. package/lib/index.d.ts.map +1 -1
  9. package/lib/storages/chrome-storage.d.ts.map +1 -1
  10. package/lib/storages/chrome-storage.js +6 -15
  11. package/lib/storages/chrome-storage.js.map +1 -1
  12. package/lib/storages/local-storage.d.ts.map +1 -1
  13. package/lib/storages/local-storage.js +1 -2
  14. package/lib/storages/local-storage.js.map +1 -1
  15. package/lib/storages/session-storage.d.ts.map +1 -1
  16. package/lib/storages/session-storage.js +1 -2
  17. package/lib/storages/session-storage.js.map +1 -1
  18. package/lib/utils/change-notifier.d.ts +1 -8
  19. package/lib/utils/change-notifier.d.ts.map +1 -1
  20. package/lib/utils/change-notifier.js +1 -10
  21. package/lib/utils/change-notifier.js.map +1 -1
  22. package/lib/utils/create-web-storage.d.ts +1 -8
  23. package/lib/utils/create-web-storage.d.ts.map +1 -1
  24. package/lib/utils/create-web-storage.js +5 -17
  25. package/lib/utils/create-web-storage.js.map +1 -1
  26. package/lib/utils/extension-storage.d.ts +2 -12
  27. package/lib/utils/extension-storage.d.ts.map +1 -1
  28. package/lib/utils/extension-storage.js +3 -14
  29. package/lib/utils/extension-storage.js.map +1 -1
  30. package/lib/utils/get-new-item.d.ts +1 -12
  31. package/lib/utils/get-new-item.d.ts.map +1 -1
  32. package/lib/utils/get-new-item.js +2 -16
  33. package/lib/utils/get-new-item.js.map +1 -1
  34. package/lib/utils/get-persisted-value.d.ts +1 -7
  35. package/lib/utils/get-persisted-value.d.ts.map +1 -1
  36. package/lib/utils/get-persisted-value.js +3 -13
  37. package/lib/utils/get-persisted-value.js.map +1 -1
  38. package/lib/utils/is-async-storage.d.ts +1 -7
  39. package/lib/utils/is-async-storage.d.ts.map +1 -1
  40. package/lib/utils/is-async-storage.js +6 -25
  41. package/lib/utils/is-async-storage.js.map +1 -1
  42. package/lib/utils/storage-event-router.d.ts +1 -5
  43. package/lib/utils/storage-event-router.d.ts.map +1 -1
  44. package/lib/utils/storage-event-router.js +3 -14
  45. package/lib/utils/storage-event-router.js.map +1 -1
  46. package/lib/utils/use-storage-handler.d.ts +1 -13
  47. package/lib/utils/use-storage-handler.d.ts.map +1 -1
  48. package/lib/utils/use-storage-handler.js +8 -78
  49. package/lib/utils/use-storage-handler.js.map +1 -1
  50. package/package.json +1 -1
  51. package/src/create-async-persisted-state.ts +14 -58
  52. package/src/create-persisted-state.ts +6 -22
  53. package/src/index.ts +1 -4
  54. package/src/storages/chrome-storage.ts +6 -18
  55. package/src/storages/local-storage.ts +1 -2
  56. package/src/storages/session-storage.ts +1 -2
  57. package/src/utils/change-notifier.ts +1 -10
  58. package/src/utils/create-web-storage.ts +5 -17
  59. package/src/utils/extension-storage.ts +3 -14
  60. package/src/utils/get-new-item.ts +2 -16
  61. package/src/utils/get-persisted-value.ts +3 -13
  62. package/src/utils/is-async-storage.ts +6 -26
  63. package/src/utils/storage-event-router.ts +3 -14
  64. package/src/utils/use-storage-handler.ts +7 -94
@@ -3,17 +3,7 @@ import { useEffect, useRef } from 'react'
3
3
  import type { AsyncStorage, Storage, StorageChange } from '../@types/storage'
4
4
  import { isFunction, isObject } from '@plq/is'
5
5
 
6
- /**
7
- * One key read out of a serialized entry. `null` is a value a caller can store,
8
- * so a stored `null` has to stay distinguishable from no value at all —
9
- * collapsing the two is what dropped a persisted `null` on its way from a change
10
- * event into state.
11
- *
12
- * A key that is not in the entry and an entry that will not parse are both
13
- * `unavailable`. They differ in why, not in what a caller does next, and the
14
- * difference that matters is reported where it happens: only a parse failure is
15
- * a defect worth a diagnostic, an entry holding other keys is routine.
16
- */
6
+ // A stored `null` is a value, so absence needs a status of its own rather than a `null` value.
17
7
  type StoredValue<T> = { status: 'stored'; value: T } | { status: 'unavailable' }
18
8
 
19
9
  function readStoredValue<T>(key: string, entry: string): StoredValue<T> {
@@ -27,15 +17,12 @@ function readStoredValue<T>(key: string, entry: string): StoredValue<T> {
27
17
  return { status: 'unavailable' }
28
18
  }
29
19
 
30
- // A foreign entry can be any JSON value, and `in` throws on a primitive. This
31
- // runs inside the adapter's notify loop, where a throw also cuts off every
32
- // listener queued behind this one.
20
+ // `in` throws on a primitive, and a throw here cuts off every listener queued behind this one.
33
21
  if (!isObject(parsed) || !(key in parsed)) return { status: 'unavailable' }
34
22
 
35
23
  return { status: 'stored', value: parsed[key] as T }
36
24
  }
37
25
 
38
- // Restores the initial value when the whole entry is removed from the storage.
39
26
  function applyRemoval<T>(
40
27
  change: StorageChange,
41
28
  itemKey: string,
@@ -46,98 +33,30 @@ function applyRemoval<T>(
46
33
 
47
34
  const oldValue = readStoredValue<T>(itemKey, change.oldValue)
48
35
  const declaredInitialValue = latestInitialValue.current
49
- // Compared against the resolved value: a factory is never equal to what it
50
- // produces, so comparing the declaration re-applies the initial value on every
51
- // removal.
36
+ // Resolved before comparing: a factory is never equal to what it produces.
52
37
  const initialValue = isFunction(declaredInitialValue) ? declaredInitialValue() : declaredInitialValue
53
38
 
54
- // An entry with no readable value for the key cannot be shown to have held the
55
- // initial value, so the fallback is applied rather than skipped. The entry is
56
- // gone either way, and stale state left in place is worse than a redundant
57
- // restore.
39
+ // Restore redundantly rather than leave stale state when the entry's old value cannot be read.
58
40
  if (oldValue.status === 'stored' && oldValue.value === initialValue) return
59
41
 
60
42
  applyValue(initialValue)
61
43
  }
62
44
 
63
- // A backend that reports nothing back leaves every record unmatched, so the list
64
- // needs a ceiling or it grows by one string per write for as long as the hook is
65
- // mounted. A bound, not a tuning: a backend that does report drains the list on
66
- // every echo, and one that reports late is what the list exists for.
67
- const MAX_PENDING_OWN_WRITES = 8
68
-
69
- /**
70
- * Remembers an entry the hook is about to write, so the change the backend
71
- * reports for it can be told apart from someone else's write.
72
- *
73
- * Recorded before the write, because a backend may report it before the call
74
- * settles. One slot was not enough: a backend free to report after its write
75
- * settles - chrome and browser storage both are - lets the next write overwrite
76
- * the record of a write still waiting to be reported, and that unsuppressed echo
77
- * then puts the earlier value back over the later one.
78
- */
79
- export function recordOwnWrite(pendingOwnWrites: React.RefObject<string[]>, item: string): void {
80
- const pending = pendingOwnWrites.current
81
-
82
- if (pending.length >= MAX_PENDING_OWN_WRITES) pending.shift()
83
-
84
- pending.push(item)
85
- }
86
-
87
- /**
88
- * Reports whether this change is a write the hook itself made, forgetting the
89
- * record when it is. A backend reports a write to every listener, the one that
90
- * made it included, and applying that echo is the storage-to-state re-sync this
91
- * hook was rebuilt without, arriving by another road: it decodes the entry again
92
- * and hands the caller an equal value with a new identity, plus a render for a
93
- * value it already holds.
94
- *
95
- * The price, accepted knowingly: for a value JSON cannot carry, the writer keeps
96
- * what it set - NaN - while every other component on the key decodes the null
97
- * that reached storage, so the two disagree until one of them remounts. Applying
98
- * the echo would settle that disagreement and bring back both the second
99
- * storage-to-state path and the render per write, so it is not the repair it
100
- * looks like.
101
- *
102
- * Forgetting on the first match keeps a later identical entry a change. Another
103
- * hook writing the same bytes is suppressed along with it, and nothing is lost:
104
- * it would have replaced a value with an equal one.
105
- */
106
- function consumeOwnWriteEcho(entry: string, pendingOwnWrites: React.RefObject<string[]>): boolean {
107
- const matched = pendingOwnWrites.current.indexOf(entry)
108
-
109
- if (matched === -1) return false
110
-
111
- // Everything recorded before the reported entry goes with it: a backend applies
112
- // writes in the order it took them and reports them in that order too, so a
113
- // record still unmatched by now has no echo left to wait for.
114
- pendingOwnWrites.current.splice(0, matched + 1)
115
-
116
- return true
117
- }
118
-
119
- // Builds the change handler. Not a hook, despite living next to one.
120
45
  function createStorageHandler<T>(
121
46
  itemKey: string,
122
47
  storageKey: string,
123
48
  applyValue: (value: T) => void,
124
49
  latestInitialValue: React.RefObject<T | (() => T)>,
125
- pendingOwnWrites: React.RefObject<string[]>,
126
50
  ) {
127
51
  return (changes: { [key: string]: StorageChange }): void => {
128
52
  for (const [key, change] of Object.entries(changes)) {
129
53
  if (key !== storageKey) continue
130
54
 
131
- // Ahead of the echo check, which needs an entry to match and a removal has
132
- // none. A removal is never one of this hook's own writes anyway: only the
133
- // entries it stores are recorded.
134
55
  if (change.newValue === null || change.newValue === undefined) {
135
56
  applyRemoval<T>(change, itemKey, applyValue, latestInitialValue)
136
57
  continue
137
58
  }
138
59
 
139
- if (consumeOwnWriteEcho(change.newValue, pendingOwnWrites)) continue
140
-
141
60
  const newValue = readStoredValue<T>(itemKey, change.newValue)
142
61
 
143
62
  if (newValue.status === 'stored') applyValue(newValue.value)
@@ -151,20 +70,14 @@ export default function useStorageHandler<T>(
151
70
  applyValue: (value: T) => void,
152
71
  storage: AsyncStorage | Storage,
153
72
  initialValue: T | (() => T),
154
- pendingOwnWrites: React.RefObject<string[]>,
155
73
  ): void {
156
- // A removal restores the initial value the hook holds now, the same one the
157
- // key-change path reads, so a caller whose default travels with its data gets
158
- // that record's default back rather than the mounted one. Tracked through a ref
159
- // rather than a dependency because an inline object or factory has a new
160
- // identity every render, which would tear the subscription down and rebuild it;
161
- // written during render, as the key the hook is rendering for is.
74
+ // A ref, not a dependency: an inline initial value changes identity every render and would churn it.
162
75
  const latestInitialValue = useRef(initialValue)
163
76
 
164
77
  latestInitialValue.current = initialValue
165
78
 
166
79
  useEffect(() => {
167
- const handleStorage = createStorageHandler<T>(key, storageKey, applyValue, latestInitialValue, pendingOwnWrites)
80
+ const handleStorage = createStorageHandler<T>(key, storageKey, applyValue, latestInitialValue)
168
81
 
169
82
  storage.onChanged.addListener(handleStorage)
170
83
 
@@ -173,5 +86,5 @@ export default function useStorageHandler<T>(
173
86
  storage.onChanged.removeListener(handleStorage)
174
87
  }
175
88
  }
176
- }, [key, storage.onChanged, storageKey, applyValue, pendingOwnWrites])
89
+ }, [key, storage.onChanged, storageKey, applyValue])
177
90
  }