Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
dai-shi committed Jul 14, 2024
1 parent 54b70c6 commit 39ec759
Showing 1 changed file with 5 additions and 8 deletions.
13 changes: 5 additions & 8 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ import { proxy, snapshot, subscribe } from 'valtio/vanilla';

type AnyFunction = (...args: never[]) => unknown;

type DeepWritable<T> = T extends object
? { -readonly [K in keyof T]: DeepWritable<T[K]> }
: T;

// TODO replace with Valtio's Snapshot type in v2
type Snapshot<T> = T extends AnyFunction
? T
Expand All @@ -11,7 +15,6 @@ type Snapshot<T> = T extends AnyFunction
: T;

type StoreWithProxy<T> = {
setState: never;
getProxyState: () => T;
};

Expand All @@ -21,10 +24,6 @@ type WithWithProxy<S, _A> = S extends { getState: () => Snapshot<infer T> }
? Write<S, StoreWithProxy<DeepWritable<T>>>
: never;

type DeepWritable<T> = T extends object
? { -readonly [K in keyof T]: DeepWritable<T[K]> }
: T;

declare module 'zustand/vanilla' {
interface StoreMutators<S, A> {
'zustand-valtio': WithWithProxy<S, A>;
Expand Down Expand Up @@ -112,17 +111,15 @@ const withProxyImpl: WithProxyImpl = (initialObject) => (set, get, api) => {
});
});
type Api = StoreApi<unknown> & StoreWithProxy<typeof initialObject>;
delete (api as Api).setState;
(api as Api).getProxyState = () => proxyState;
subscribe(proxyState, updateState, true);
api.subscribe(() => {
if (!updating) {
// HACK for persist hydration
const state = get();
applyChanges(
proxyState,
snapshot(proxyState) as typeof proxyState,
state as typeof proxyState,
get() as typeof proxyState,
);
}
});
Expand Down

0 comments on commit 39ec759

Please sign in to comment.