Skip to content

Commit 1584b74

Browse files
authored
fix(kit): init shared state on rpc trusted (#150)
1 parent bfc5248 commit 1584b74

File tree

1 file changed

+41
-26
lines changed

1 file changed

+41
-26
lines changed

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

Lines changed: 41 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -51,33 +51,48 @@ export function createRpcSharedStateClientHost(rpc: DevToolsRpcClient): RpcShare
5151
if (sharedState.has(key)) {
5252
return sharedState.get(key)!
5353
}
54-
rpc.callEvent('vite:internal:rpc:server-state:subscribe', key)
55-
if (options?.initialValue !== undefined) {
56-
const state = createSharedState<T>({
57-
initialValue: options.initialValue,
58-
enablePatches: false,
59-
})
60-
sharedState.set(key, state)
61-
rpc.call('vite:internal:rpc:server-state:get', key)
62-
.then((serverState) => {
63-
state.mutate(() => serverState)
64-
})
65-
.catch((error) => {
66-
console.error('Error getting server state', error)
67-
})
68-
registerSharedState(key, state)
69-
return state
70-
}
71-
else {
72-
const initialValue = await rpc.call('vite:internal:rpc:server-state:get', key) as T
73-
const state = createSharedState<T>({
74-
initialValue,
75-
enablePatches: false,
76-
})
77-
sharedState.set(key, state)
78-
registerSharedState(key, state)
79-
return state
54+
55+
const state = createSharedState<T>({
56+
initialValue: options?.initialValue as T,
57+
enablePatches: false,
58+
})
59+
60+
async function initSharedState() {
61+
rpc.callEvent('vite:internal:rpc:server-state:subscribe', key)
62+
if (options?.initialValue !== undefined) {
63+
sharedState.set(key, state)
64+
rpc.call('vite:internal:rpc:server-state:get', key)
65+
.then((serverState) => {
66+
state.mutate(() => serverState)
67+
})
68+
.catch((error) => {
69+
console.error('Error getting server state', error)
70+
})
71+
registerSharedState(key, state)
72+
return state
73+
}
74+
else {
75+
const initialValue = await rpc.call('vite:internal:rpc:server-state:get', key) as T
76+
state.mutate(() => initialValue)
77+
sharedState.set(key, state)
78+
registerSharedState(key, state)
79+
return state
80+
}
8081
}
82+
83+
return new Promise<SharedState<T>>((resolve) => {
84+
if (!rpc.isTrusted) {
85+
resolve(state)
86+
rpc.events.on('rpc:is-trusted:updated', (isTrusted) => {
87+
if (isTrusted) {
88+
initSharedState()
89+
}
90+
})
91+
}
92+
else {
93+
initSharedState().then(resolve)
94+
}
95+
})
8196
},
8297
}
8398
}

0 commit comments

Comments
 (0)