Files
effect-fc/packages/effect-fc/src/Hooks/useFork.ts
Julien Valverdé 9a3c91b50b
All checks were successful
Publish / publish (push) Successful in 21s
Lint / lint (push) Successful in 12s
0.1.4 (#5)
Co-authored-by: Julien Valverdé <julien.valverde@mailo.com>
Reviewed-on: #5
2025-10-02 18:18:23 +02:00

33 lines
1.3 KiB
TypeScript

import { Effect, ExecutionStrategy, Runtime, Scope } from "effect"
import * as React from "react"
import { closeScope } from "./internal.js"
import type { ScopeOptions } from "./ScopeOptions.js"
export const useFork: {
<E, R>(
effect: () => Effect.Effect<void, E, R>,
deps?: React.DependencyList,
options?: Runtime.RunForkOptions & ScopeOptions,
): Effect.Effect<void, never, Exclude<R, Scope.Scope>>
} = Effect.fnUntraced(function* <E, R>(
effect: () => Effect.Effect<void, E, R>,
deps?: React.DependencyList,
options?: Runtime.RunForkOptions & ScopeOptions,
) {
const runtime = yield* Effect.runtime<Exclude<R, Scope.Scope>>()
React.useEffect(() => {
const scope = Runtime.runSync(runtime)(options?.scope
? Scope.fork(options.scope, options?.finalizerExecutionStrategy ?? ExecutionStrategy.sequential)
: Scope.make(options?.finalizerExecutionStrategy ?? ExecutionStrategy.sequential)
)
Runtime.runFork(runtime)(Effect.provideService(effect(), Scope.Scope, scope), { ...options, scope })
return () => closeScope(scope, runtime, {
...options,
finalizerExecutionMode: options?.finalizerExecutionMode ?? "fork",
})
// biome-ignore lint/correctness/useExhaustiveDependencies: use of React.DependencyList
}, deps)
})