Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(core): emit local settings value immediately upon subscription #7560

Merged
merged 1 commit into from
Sep 30, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading