From fed8ec051a541b8ddc331d9dc3e9ef62eed96c65 Mon Sep 17 00:00:00 2001 From: unadlib Date: Sat, 21 Dec 2024 01:34:16 +0800 Subject: [PATCH] fix(zustand): fix update state issue --- packages/coaction-zustand/src/index.ts | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/packages/coaction-zustand/src/index.ts b/packages/coaction-zustand/src/index.ts index 9c9d339..cf8c495 100644 --- a/packages/coaction-zustand/src/index.ts +++ b/packages/coaction-zustand/src/index.ts @@ -14,13 +14,27 @@ export const bindZustand = ((initializer: StateCreator) => const internalBindZustand = createBinder({ handleStore: (store, rawState, state, internal) => { if (zustandStore.getState() === internal.rootState) return; + let isCoactionUpdated = false; internal.rootState = zustandStore.getState() as object; coactionStore = store; zustandStore.subscribe(() => { + if (!isCoactionUpdated) { + internal.rootState = zustandStore.getState() as object; + if (coactionStore.share === 'client') { + throw new Error('client zustand store cannot be updated'); + } else if (coactionStore.share === 'main') { + // TODO: emit to all clients + } + } internal.listeners.forEach((listener) => listener()); }); internal.updateImmutable = (state: any) => { - zustandStore.setState(state, true); + isCoactionUpdated = true; + try { + zustandStore.setState(state, true); + } finally { + isCoactionUpdated = false; + } }; }, handleState: (externalState) => {