Skip to content

Commit 559db01

Browse files
useComputed hook
1 parent 1278422 commit 559db01

3 files changed

Lines changed: 7 additions & 16 deletions

File tree

Original file line numberDiff line numberDiff line change
@@ -1,36 +1,28 @@
11
import { useEffect, useState, useContext } from 'react';
2-
// @ts-ignore
32
import SyncStateReactContext from '../components/Context';
4-
import { produceWithPatches, enablePatches } from 'immer';
53
import { ComputeCallback, DocStore } from '@syncstate/core';
6-
enablePatches();
7-
8-
//create your forceUpdate hook
9-
function useForceUpdate() {
10-
const [value, setValue] = useState(0); // integer state
11-
return () => setValue(value => ++value); // update the state to force render
12-
}
134

145
export function useComputed(subtree: string, computeCallback: ComputeCallback) {
15-
// const forceUpdate = useForceUpdate();
166
const store: DocStore = useContext(SyncStateReactContext);
177

188
const [computedValue, setComputedValue] = useState(undefined);
199

2010
useEffect(() => {
21-
const dispose = store.compute(subtree, (getValue, change) => {
11+
const dispose = store.compute(subtree, (getValue: any, change: any) => {
2212
console.log('$$$$compute observer hook');
2313
const computed = computeCallback(getValue, change);
2414

2515
setComputedValue(computed);
2616
});
17+
18+
return dispose;
2719
}, []);
2820

2921
console.log('computed value through hook', computedValue);
3022

3123
return [computedValue];
3224
}
3325

34-
// export function useDoc(path: string = '', depth: number = 1) {
35-
// return useSyncState('doc', path, depth);
36-
// }
26+
export function useComputedDoc(computeCallback: ComputeCallback) {
27+
return useComputed('doc', computeCallback);
28+
}

src/hooks/useDoc.ts

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
import { useEffect, useState, useContext } from 'react';
22
import SyncStateReactContext from '../components/Context';
3-
import { produceWithPatches, enablePatches } from 'immer';
4-
enablePatches();
53

64
//create your forceUpdate hook
75
function useForceUpdate() {

src/index.tsx

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
export { useDoc, useSyncState } from './hooks/useDoc';
2+
export { useComputed } from './hooks/useComputed';
23
export { Provider } from './components/Provider';
34
export { SyncStateReactContext } from './components/Context';

0 commit comments

Comments
 (0)