Skip to content

Commit 1799a4e

Browse files
tim-smartdatner
authored andcommitted
add makeUseResult
1 parent 19c3c1b commit 1799a4e

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

src/hooks/useResultCallback.ts

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { pipe } from "@effect/data/Function"
2+
import * as Hash from "@effect/data/Hash"
23
import * as Effect from "@effect/io/Effect"
34
import type * as Fiber from "@effect/io/Fiber"
45
import * as Ref from "@effect/io/Ref"
@@ -8,6 +9,7 @@ import type { ResultBag } from "effect-react/hooks/useResultBag"
89
import { initialTrackedProps, makeResultBag, updateTrackedProps } from "effect-react/hooks/useResultBag"
910
import type { RuntimeContext } from "effect-react/internal/runtimeContext"
1011
import * as Result from "effect-react/Result"
12+
import type { DependencyList } from "react"
1113
import { useCallback, useContext, useRef, useSyncExternalStore } from "react"
1214

1315
class FiberStore<R, E, A> {
@@ -125,3 +127,28 @@ export const makeUseResultCallback: <R>(
125127
}, [f])
126128
return [resultBag, run] as const
127129
}
130+
131+
export const makeUseResult = <R>(
132+
runtimeContext: RuntimeContext<R>
133+
) =>
134+
<R0 extends R, E, A>(
135+
evaluate: () => Stream.Stream<R0, E, A>,
136+
deps: DependencyList
137+
): ResultBag<E, A> => {
138+
const runtime = useContext(runtimeContext)
139+
const storeRef = useRef<FiberStore<R0, E, A>>(undefined as any)
140+
if (storeRef.current === undefined) {
141+
storeRef.current = new FiberStore(runtime)
142+
}
143+
const resultBag = useSyncExternalStore(
144+
storeRef.current.subscribe,
145+
storeRef.current.snapshot
146+
)
147+
const depsHash = useRef<number>(null as any)
148+
const currentDepsHash = Hash.array(deps)
149+
if (depsHash.current !== currentDepsHash) {
150+
depsHash.current = currentDepsHash
151+
storeRef.current.run(evaluate())
152+
}
153+
return resultBag
154+
}

0 commit comments

Comments
 (0)