0.1.3 (#5)
All checks were successful
Publish / publish (push) Successful in 24s
Lint / lint (push) Successful in 16s

Co-authored-by: Julien Valverdé <julien.valverde@mailo.com>
Reviewed-on: https://gitea:3000/Thilawyn/reffuse/pulls/5
This commit was merged in pull request #5.
This commit is contained in:
Julien Valverdé
2025-03-11 01:44:37 +01:00
parent 2aa0c64a7c
commit a7b5a32071
28 changed files with 707 additions and 109 deletions

View File

@@ -0,0 +1,55 @@
import type * as AsyncData from "@typed/async-data"
import { type Cause, type Context, Effect, type Fiber, Layer, type Option, type Stream, type SubscriptionRef } from "effect"
import * as React from "react"
import { ReffuseExtension, type ReffuseHelpers } from "reffuse"
import * as QueryRunner from "./QueryRunner.js"
import type * as QueryService from "./QueryService.js"
export interface UseQueryProps<K extends readonly unknown[], A, E, R> {
readonly key: Stream.Stream<K>
readonly query: (key: K) => Effect.Effect<A, E, R>
readonly refreshOnWindowFocus?: boolean
}
export interface UseQueryResult<K extends readonly unknown[], A, E> {
readonly latestKey: SubscriptionRef.SubscriptionRef<Option.Option<K>>
readonly state: SubscriptionRef.SubscriptionRef<AsyncData.AsyncData<A, E>>
readonly refresh: Effect.Effect<Fiber.RuntimeFiber<void, Cause.NoSuchElementException>>
readonly layer: <Self, Id extends string>(
tag: Context.TagClass<Self, Id, QueryService.QueryService<K, A, E>>
) => Layer.Layer<Self>
}
export const QueryExtension = ReffuseExtension.make(() => ({
useQuery<K extends readonly unknown[], A, E, R>(
this: ReffuseHelpers.ReffuseHelpers<R>,
props: UseQueryProps<K, A, E, R>,
): UseQueryResult<K, A, E> {
const runner = this.useMemo(() => QueryRunner.make({
key: props.key,
query: props.query,
}), [props.key])
this.useFork(() => runner.fetchOnKeyChange, [runner])
this.useFork(() => (props.refreshOnWindowFocus ?? true)
? runner.refreshOnWindowFocus
: Effect.void,
[props.refreshOnWindowFocus, runner])
return React.useMemo(() => ({
latestKey: runner.latestKeyRef,
state: runner.stateRef,
refresh: runner.forkRefresh,
layer: tag => Layer.succeed(tag, {
latestKey: runner.latestKeyRef,
state: runner.stateRef,
refresh: runner.forkRefresh,
}),
}), [runner])
}
}))