Skip to content

Commit

Permalink
attach proxyState
Browse files Browse the repository at this point in the history
  • Loading branch information
dai-shi committed Apr 25, 2024
1 parent 971ea51 commit 6484ced
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 7 deletions.
4 changes: 2 additions & 2 deletions examples/01_counter/src/app.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { createWithProxy } from 'zustand-valtio';

const [useCounterState, counterState] = createWithProxy({ count: 0 });
const useCounterState = createWithProxy({ count: 0 });

const Counter = () => {
const count = useCounterState((state) => state.count);
const inc = () => ++counterState.count;
const inc = () => ++useCounterState.proxyState.count;
return (
<>
<div>Count: {count}</div>
Expand Down
14 changes: 9 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,17 @@ import { createStore, useStore } from 'zustand';
import { proxy, snapshot, subscribe } from 'valtio/vanilla';
import type { INTERNAL_Snapshot as Snapshot } from 'valtio/vanilla';

export function createWithProxy<T extends object>(initialObject: T) {
export function createWithProxy<T extends object>(
initialObject: T,
): {
<Slice>(selector: (state: Snapshot<T>) => Slice): Slice;
proxyState: T;
} {
const proxyState = proxy(initialObject);
const store = createStore(() => snapshot(proxyState));
const unsubscribe = subscribe(proxyState, () =>
store.setState(snapshot(proxyState), true),
);
subscribe(proxyState, () => store.setState(snapshot(proxyState), true));
const useProxyState = <Slice>(selector: (state: Snapshot<T>) => Slice) =>
useStore(store, selector);
return [useProxyState, proxyState, unsubscribe] as const;
useProxyState.proxyState = proxyState;
return useProxyState;
}

0 comments on commit 6484ced

Please sign in to comment.