react-native-cloud-sync 0.3.0 → 0.4.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.
package/src/hooks.ts CHANGED
@@ -171,6 +171,300 @@ export function useCloudItem<T = unknown>(
171
171
  return { value, loading, error, setValue, remove, refresh: read }
172
172
  }
173
173
 
174
+ export interface UseCloudItemsResult<T> {
175
+ /**
176
+ * Parsed value per key. A key mapped to `null` was fetched and does not
177
+ * exist; a key absent from this object has not been fetched yet.
178
+ */
179
+ values: Record<string, T | null>
180
+ /** True only during the initial fetch of `keys`, and during an explicit `refresh()`. */
181
+ loading: boolean
182
+ /** The last read or write failure, or null. Cleared by the next success. */
183
+ error: CloudSyncError | null
184
+ /** Writes through to the store and updates local state optimistically. */
185
+ setValue: (key: string, next: T) => Promise<void>
186
+ remove: (key: string) => Promise<void>
187
+ /** Re-fetches every key currently tracked. */
188
+ refresh: () => Promise<void>
189
+ }
190
+
191
+ export interface UseCloudItemsOptions<T> {
192
+ parse?: (raw: string) => T
193
+ serialize?: (value: T) => string
194
+ /**
195
+ * Re-fetch a key when another device changes it. Default true.
196
+ *
197
+ * An event naming no keys (an account or quota event) re-fetches every
198
+ * tracked key, same as `useCloudItem`.
199
+ */
200
+ watch?: boolean
201
+ }
202
+
203
+ /**
204
+ * Binds a list of keys to component state with one batched `multiGet`.
205
+ *
206
+ * The multi-key sibling of `useCloudItem` - a screen with many cloud-backed
207
+ * records (a list, one key per item) otherwise ends up calling `useCloudItem`
208
+ * once per row: one `getItem` and one `onRemoteChange` subscription each,
209
+ * instead of a single batched read.
210
+ *
211
+ * Only ever fetches keys it does not already hold an answer for. Mount,
212
+ * `refresh()`, and a matching remote-change event all fetch normally, but a
213
+ * key merely joining the tracked list - because a caller like
214
+ * `useCloudCollection` just added it after a local write - is never
215
+ * re-fetched on that account alone, so a slow fetch elsewhere in the list
216
+ * can't land a stale value on top of a write that already resolved locally.
217
+ *
218
+ * ```tsx
219
+ * const { values, setValue } = useCloudItems<Note>(store, noteIds)
220
+ * ```
221
+ */
222
+ export function useCloudItems<T = unknown>(
223
+ store: CloudStore,
224
+ keys: string[],
225
+ options: UseCloudItemsOptions<T> = {}
226
+ ): UseCloudItemsResult<T> {
227
+ const {
228
+ parse = JSON.parse as (raw: string) => T,
229
+ serialize = JSON.stringify as (value: T) => string,
230
+ watch = true,
231
+ } = options
232
+
233
+ const [values, setValuesState] = useState<Record<string, T | null>>({})
234
+ const [loading, setLoading] = useState(true)
235
+ const [error, setError] = useState<CloudSyncError | null>(null)
236
+
237
+ const mounted = useRef(true)
238
+ useEffect(() => {
239
+ mounted.current = true
240
+ return () => {
241
+ mounted.current = false
242
+ }
243
+ }, [])
244
+
245
+ const parseRef = useRef(parse)
246
+ parseRef.current = parse
247
+
248
+ const keysRef = useRef(keys)
249
+ keysRef.current = keys
250
+ const keysSignature = JSON.stringify(keys)
251
+
252
+ // Latest values alongside the state, so effects can read "do we already
253
+ // have this key" without taking `values` itself as a dependency.
254
+ const valuesRef = useRef<Record<string, T | null>>(values)
255
+ const setValues = useCallback(
256
+ (updater: (prev: Record<string, T | null>) => Record<string, T | null>): void => {
257
+ setValuesState((prev) => {
258
+ const next = updater(prev)
259
+ valuesRef.current = next
260
+ return next
261
+ })
262
+ },
263
+ []
264
+ )
265
+
266
+ // Per-key ticket, not one shared counter: two fetches for disjoint keys
267
+ // run concurrently (an initial load still in flight plus a remote event for
268
+ // a key that just appeared), and a shared ticket would let the second
269
+ // invalidate the first's unrelated result.
270
+ const keyTicket = useRef<Map<string, number>>(new Map())
271
+ const bump = (key: string): number => {
272
+ const next = (keyTicket.current.get(key) ?? 0) + 1
273
+ keyTicket.current.set(key, next)
274
+ return next
275
+ }
276
+
277
+ const fetchKeys = useCallback(async (toFetch: string[]): Promise<void> => {
278
+ if (toFetch.length === 0) return
279
+ const mine = new Map(toFetch.map(k => [k, bump(k)]))
280
+
281
+ try {
282
+ const pairs = await store.multiGet(toFetch)
283
+ if (!mounted.current) return
284
+ setValues((prev) => {
285
+ const next = { ...prev }
286
+ for (const [k, raw] of pairs) {
287
+ // A write or a newer fetch already claimed this key - this answer
288
+ // is no longer the current one.
289
+ if (keyTicket.current.get(k) !== mine.get(k)) continue
290
+ next[k] = raw == null ? null : parseRef.current(raw)
291
+ }
292
+ return next
293
+ })
294
+ setError(null)
295
+ }
296
+ catch (e) {
297
+ if (!mounted.current) return
298
+ // Only surface the failure if at least one of these keys is still
299
+ // uncontested - a fetch overtaken by a write or another fetch failing
300
+ // is not new information.
301
+ const stillCurrent = toFetch.some(k => keyTicket.current.get(k) === mine.get(k))
302
+ if (stillCurrent) setError(normalizeError(e))
303
+ }
304
+ }, [store, setValues])
305
+
306
+ // Fetches keys new to the tracked list and drops values for keys no longer
307
+ // in it. Doubles as the initial load: on mount every key is "missing".
308
+ const hasLoadedOnce = useRef(false)
309
+ useEffect(() => {
310
+ const current = keysRef.current
311
+ const missing = current.filter(k => !(k in valuesRef.current))
312
+
313
+ const keep = new Set(current)
314
+ setValues((prev) => {
315
+ let changed = false
316
+ const next: Record<string, T | null> = {}
317
+ for (const k of Object.keys(prev))
318
+ if (keep.has(k)) next[k] = prev[k]
319
+ else changed = true
320
+
321
+ return changed ? next : prev
322
+ })
323
+
324
+ if (!hasLoadedOnce.current) {
325
+ hasLoadedOnce.current = true
326
+ setLoading(true)
327
+ void fetchKeys(missing).finally(() => {
328
+ if (mounted.current) setLoading(false)
329
+ })
330
+ }
331
+ else if (missing.length > 0) {
332
+ void fetchKeys(missing)
333
+ }
334
+ }, [keysSignature, fetchKeys, setValues])
335
+
336
+ useEffect(() => {
337
+ if (!watch) return
338
+ return store.onRemoteChange((e) => {
339
+ if (e.keys.length === 0) {
340
+ void fetchKeys(keysRef.current)
341
+ return
342
+ }
343
+ const intersecting = e.keys.filter(k => keysRef.current.includes(k))
344
+ if (intersecting.length > 0) void fetchKeys(intersecting)
345
+ })
346
+ }, [store, watch, fetchKeys])
347
+
348
+ const setValue = useCallback(async (key: string, next: T): Promise<void> => {
349
+ bump(key)
350
+ setValues(prev => ({ ...prev, [key]: next }))
351
+ try {
352
+ await store.setItem(key, serialize(next))
353
+ if (mounted.current) setError(null)
354
+ }
355
+ catch (e) {
356
+ if (mounted.current) setError(normalizeError(e))
357
+ throw e
358
+ }
359
+ }, [store, serialize, setValues])
360
+
361
+ const remove = useCallback(async (key: string): Promise<void> => {
362
+ bump(key)
363
+ setValues(prev => ({ ...prev, [key]: null }))
364
+ try {
365
+ await store.removeItem(key)
366
+ if (mounted.current) setError(null)
367
+ }
368
+ catch (e) {
369
+ if (mounted.current) setError(normalizeError(e))
370
+ throw e
371
+ }
372
+ }, [store, setValues])
373
+
374
+ const refresh = useCallback(async (): Promise<void> => {
375
+ setLoading(true)
376
+ try {
377
+ await fetchKeys(keysRef.current)
378
+ }
379
+ finally {
380
+ if (mounted.current) setLoading(false)
381
+ }
382
+ }, [fetchKeys])
383
+
384
+ return { values, loading, error, setValue, remove, refresh }
385
+ }
386
+
387
+ export interface UseCloudCollectionResult<T> extends UseCloudItemsResult<T> {
388
+ /** Keys currently in the collection. */
389
+ keys: string[]
390
+ }
391
+
392
+ /**
393
+ * Live-binds every key starting with `prefix` to component state.
394
+ *
395
+ * Adds the membership index `useCloudItems` needs but does not derive
396
+ * itself: `getAllKeys()` filtered by prefix on mount and after any remote
397
+ * change that could plausibly have added or removed a member, then
398
+ * `useCloudItems` for the values.
399
+ *
400
+ * A `setValue` for a key not seen before joins the collection immediately -
401
+ * a newly created record should appear in its own list without waiting on a
402
+ * round trip to confirm it.
403
+ *
404
+ * ```tsx
405
+ * const { keys, values, setValue, remove } = useCloudCollection<Note>(store, 'note:')
406
+ * ```
407
+ */
408
+ export function useCloudCollection<T = unknown>(
409
+ store: CloudStore,
410
+ prefix: string,
411
+ options: UseCloudItemsOptions<T> = {}
412
+ ): UseCloudCollectionResult<T> {
413
+ const { watch = true } = options
414
+
415
+ const [keys, setKeys] = useState<string[]>([])
416
+ const mounted = useRef(true)
417
+ useEffect(() => {
418
+ mounted.current = true
419
+ return () => {
420
+ mounted.current = false
421
+ }
422
+ }, [])
423
+
424
+ const listKeys = useCallback(async (): Promise<void> => {
425
+ const all = await store.getAllKeys()
426
+ if (!mounted.current) return
427
+ setKeys(all.filter(k => k.startsWith(prefix)))
428
+ }, [store, prefix])
429
+
430
+ useEffect(() => {
431
+ void listKeys()
432
+ }, [listKeys])
433
+
434
+ useEffect(() => {
435
+ if (!watch) return
436
+ return store.onRemoteChange((e) => {
437
+ // A prefix collection can gain or lose members on another device, not
438
+ // just change the value of one already in it - re-list on an opaque
439
+ // event too, not only one that names a key under this prefix.
440
+ if (e.keys.length > 0 && !e.keys.some(k => k.startsWith(prefix))) return
441
+ void listKeys()
442
+ })
443
+ }, [store, prefix, watch, listKeys])
444
+
445
+ const items = useCloudItems<T>(store, keys, options)
446
+
447
+ const setValue = useCallback(async (key: string, next: T): Promise<void> => {
448
+ if (key.startsWith(prefix)) setKeys(prev => (prev.includes(key) ? prev : [...prev, key]))
449
+ await items.setValue(key, next)
450
+ }, [items, prefix])
451
+
452
+ const remove = useCallback(async (key: string): Promise<void> => {
453
+ await items.remove(key)
454
+ setKeys(prev => (prev.includes(key) ? prev.filter(k => k !== key) : prev))
455
+ }, [items])
456
+
457
+ const refresh = useCallback(async (): Promise<void> => {
458
+ // Concurrent, not sequential: a key that only `listKeys` turns up gets
459
+ // its value shortly after anyway, through the same membership-diff
460
+ // effect that handles a live remote event, so there is nothing to gain
461
+ // from waiting for the listing before starting `items.refresh()`.
462
+ await Promise.all([listKeys(), items.refresh()])
463
+ }, [listKeys, items])
464
+
465
+ return { ...items, setValue, remove, refresh, keys }
466
+ }
467
+
174
468
  export interface UseAccountStatusResult {
175
469
  status: AccountStatus | null
176
470
  /**
package/src/index.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * react-native-cloud-sync
3
3
  *
4
- * iCloud key-value store, CloudKit and Google Drive behind one API, on iOS,
5
- * Android and the web, on both React Native architectures.
4
+ * iCloud key-value store, CloudKit, iCloud Drive and Google Drive behind one API,
5
+ * on iOS, Android and the web, on both React Native architectures.
6
6
  */
7
7
 
8
8
  // Providers, each usable directly.