Skip to content

Commit

Permalink
fix(core): emit setting from localStorage immediately upon subscripti…
Browse files Browse the repository at this point in the history
…on (#7560)
  • Loading branch information
bjoerge authored Sep 30, 2024
1 parent d2ca86d commit 1e79797
Showing 1 changed file with 3 additions and 14 deletions.
17 changes: 3 additions & 14 deletions packages/sanity/src/core/store/key-value/localStorageSWR.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,16 @@
import {isEqual} from 'lodash'
import {fromEvent, merge, NEVER} from 'rxjs'
import {distinctUntilChanged, filter, map, tap} from 'rxjs/operators'
import {merge, of} from 'rxjs'
import {distinctUntilChanged, tap} from 'rxjs/operators'

import {localStoreStorage} from './storage/localStoreStorage'
import {type KeyValueStore, type KeyValueStoreValue} from './types'

// Whether or not to enable instant user sync between tabs
// if set to true, the setting will update instantly across all tabs
const ENABLE_CROSS_TAB_SYNC = false

/**
* Wraps a KeyValueStore and adds Stale-While-Revalidate (SWR) behavior to it
*/
export function withLocalStorageSWR(wrappedStore: KeyValueStore): KeyValueStore {
const storageEvent = ENABLE_CROSS_TAB_SYNC ? fromEvent<StorageEvent>(window, 'storage') : NEVER

function getKey(key: string) {
const lsUpdates = storageEvent.pipe(
filter((event) => event.key === key),
map(() => localStoreStorage.getKey(key)),
)

return merge(lsUpdates, wrappedStore.getKey(key)).pipe(
return merge(of(localStoreStorage.getKey(key)), wrappedStore.getKey(key)).pipe(
distinctUntilChanged(isEqual),
tap((value) => {
localStoreStorage.setKey(key, value)
Expand Down

0 comments on commit 1e79797

Please sign in to comment.