Skip to content

Commit

Permalink
Merge pull request #22 from nabla-studio/DavideSegullo/fix-broadcast
Browse files Browse the repository at this point in the history
fix(store): 🐛 fix tab sync
  • Loading branch information
DavideSegullo authored Nov 23, 2023
2 parents 6d0b659 + ee96821 commit faad3cf
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
24 changes: 21 additions & 3 deletions packages/store/src/middlewares/shared.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { AppState } from '../types';
import type { StateCreator } from 'zustand/vanilla';

export interface SharedOptions {
Expand All @@ -6,7 +7,7 @@ export interface SharedOptions {
enabled?: boolean;
}

export type SharedType = <T>(
export type SharedType = <T extends AppState>(
f: StateCreator<T, [], []>,
options?: SharedOptions,
) => StateCreator<T, [], []>;
Expand Down Expand Up @@ -35,9 +36,9 @@ export const shared: SharedType =
const channel = new BroadcastChannel(options.name);

const set_: typeof set = (...args) => {
const prevState = get() as { [k: string]: unknown };
const prevState = get() as never as { [k: string]: unknown };
set(...args);
const currentState = get() as { [k: string]: unknown };
const currentState = get() as never as { [k: string]: unknown };
const stateUpdates: { [k: string]: unknown } = {};

/** sync only updated state to avoid un-necessary re-renders */
Expand All @@ -64,5 +65,22 @@ export const shared: SharedType =
set(e.data);
};
}

store.subscribe((state) => {
if (
state.walletName &&
!state.wallet &&
state.status === 'CONNECTED' &&
(state.reconnectionStatus === 'IDLE' ||
state.reconnectionStatus === 'RECONNECTED')
) {
const wallet = get().wallets.find(
(el) => el.options.name === state.walletName,
);

get().setWallet(wallet);
}
});

return f(set_, get, store);
};
4 changes: 2 additions & 2 deletions packages/store/src/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,14 @@ import {
createSignSlice,
} from './slices';
import { createStore } from 'zustand/vanilla';
import type { AppState, Config } from './types';
import type { Config } from './types';
import { defaultPersistOptions, emptyPersistOptions } from './configs';
import { shared, defaultSharedOptions } from './middlewares';

export let store = createStore(
subscribeWithSelector(
persist(
shared<AppState>((...props) => ({
shared((...props) => ({
...createConfigSlice(...props),
...createConnectSlice(...props),
...createAccountSlice(...props),
Expand Down

0 comments on commit faad3cf

Please sign in to comment.