Skip to content

Commit 586c6bb

Browse files
antfuclaude
andcommitted
fix(kit): merge initialValue defaults when syncing client shared state
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
1 parent 923e9f9 commit 586c6bb

File tree

1 file changed

+17
-4
lines changed

1 file changed

+17
-4
lines changed

packages/kit/src/client/rpc-shared-state.ts

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,26 @@ import { createSharedState } from '../utils/shared-state'
55

66
export function createRpcSharedStateClientHost(rpc: DevToolsRpcClient): RpcSharedStateHost {
77
const sharedState = new Map<string, SharedState<any>>()
8+
const initialValues = new Map<string, any>()
89
const isStaticBackend = rpc.connectionMeta.backend === 'static'
910

11+
function mergeWithInitialValue(key: string, serverState: any): any {
12+
const initial = initialValues.get(key)
13+
if (initial && typeof initial === 'object' && !Array.isArray(initial)
14+
&& typeof serverState === 'object' && !Array.isArray(serverState)) {
15+
return { ...initial, ...serverState }
16+
}
17+
return serverState
18+
}
19+
1020
rpc.client.register({
1121
name: 'devtoolskit:internal:rpc:client-state:updated',
1222
type: 'event',
1323
handler: (key: string, fullState: any, syncId: string) => {
1424
const state = sharedState.get(key)
1525
if (!state || state.syncIds.has(syncId))
1626
return
17-
state.mutate(() => fullState, syncId)
27+
state.mutate(() => mergeWithInitialValue(key, fullState), syncId)
1828
},
1929
})
2030

@@ -52,6 +62,9 @@ export function createRpcSharedStateClientHost(rpc: DevToolsRpcClient): RpcShare
5262
return {
5363
keys: () => Array.from(sharedState.keys()),
5464
get: async <T extends object>(key: string, options?: RpcSharedStateGetOptions<T>) => {
65+
if (options?.initialValue !== undefined) {
66+
initialValues.set(key, options.initialValue)
67+
}
5568
if (sharedState.has(key)) {
5669
return sharedState.get(key)!
5770
}
@@ -70,7 +83,7 @@ export function createRpcSharedStateClientHost(rpc: DevToolsRpcClient): RpcShare
7083
rpc.call('devtoolskit:internal:rpc:server-state:get', key)
7184
.then((serverState) => {
7285
if (serverState !== undefined)
73-
state.mutate(() => serverState)
86+
state.mutate(() => mergeWithInitialValue(key, serverState))
7487
})
7588
.catch((error) => {
7689
console.error('Error getting server state', error)
@@ -79,8 +92,8 @@ export function createRpcSharedStateClientHost(rpc: DevToolsRpcClient): RpcShare
7992
return state
8093
}
8194
else {
82-
const initialValue = await rpc.call('devtoolskit:internal:rpc:server-state:get', key) as T
83-
state.mutate(() => initialValue)
95+
const serverValue = await rpc.call('devtoolskit:internal:rpc:server-state:get', key) as T
96+
state.mutate(() => mergeWithInitialValue(key, serverValue))
8497
sharedState.set(key, state)
8598
registerSharedState(key, state)
8699
return state

0 commit comments

Comments
 (0)