functype-react 2.2.0 → 2.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +25 -14
- package/dist/AsyncState-CwxtGl5L.d.ts +45 -0
- package/dist/async/AsyncState.d.ts +2 -2
- package/dist/async/AsyncState.js +2 -1
- package/dist/async/AsyncState.js.map +1 -0
- package/dist/async/index.d.ts +1 -1
- package/dist/async/useIO.d.ts +6 -6
- package/dist/async/useIO.js +1 -1
- package/dist/async/useIO.js.map +1 -1
- package/dist/query/queryState.d.ts +1 -1
- package/dist/query/useIOMutation.d.ts +1 -1
- package/dist/query/useIOMutation.js.map +1 -1
- package/dist/query/useIOMutationState.d.ts +2 -7
- package/dist/query/useIOMutationState.js +1 -1
- package/dist/query/useIOMutationState.js.map +1 -1
- package/dist/query/useIOQueryState.d.ts +2 -7
- package/dist/query/useIOQueryState.js +1 -1
- package/dist/query/useIOQueryState.js.map +1 -1
- package/package.json +2 -2
- package/dist/AsyncState-zTPspeWC.d.ts +0 -20
package/README.md
CHANGED
|
@@ -52,7 +52,7 @@ const parsed = useTry<Config>() // value: Try<Config>
|
|
|
52
52
|
|
|
53
53
|
## Tier 2 — pattern matching in JSX
|
|
54
54
|
|
|
55
|
-
```tsx
|
|
55
|
+
```tsx ignore
|
|
56
56
|
import { Match, MatchOption } from "functype-react"
|
|
57
57
|
|
|
58
58
|
<MatchOption value={user}
|
|
@@ -73,7 +73,7 @@ Omitting a `_tag` case is a compile error.
|
|
|
73
73
|
|
|
74
74
|
## Tier 3 — async / IO
|
|
75
75
|
|
|
76
|
-
```
|
|
76
|
+
```tsx ignore
|
|
77
77
|
import { Http } from "functype/fetch"
|
|
78
78
|
import { useIO } from "functype-react/async"
|
|
79
79
|
|
|
@@ -89,7 +89,7 @@ On unmount or a `deps` change the signal aborts, and the effect stops at its nex
|
|
|
89
89
|
|
|
90
90
|
For React 19 `use()` + Suspense:
|
|
91
91
|
|
|
92
|
-
```tsx
|
|
92
|
+
```tsx ignore
|
|
93
93
|
import { AsyncBoundary, useIOValue } from "functype-react/async"
|
|
94
94
|
|
|
95
95
|
function UserPanel({ id }: { id: string }) {
|
|
@@ -106,7 +106,7 @@ function UserPanel({ id }: { id: string }) {
|
|
|
106
106
|
|
|
107
107
|
## Tier 4 — forms with accumulating validation
|
|
108
108
|
|
|
109
|
-
```
|
|
109
|
+
```tsx ignore
|
|
110
110
|
import { useValidatedForm, valid, invalid, type Validated } from "functype-react/forms"
|
|
111
111
|
import { List } from "functype"
|
|
112
112
|
|
|
@@ -115,7 +115,7 @@ type SignupForm = { email: string; age: number }
|
|
|
115
115
|
const validate = (s: SignupForm): Validated<string, SignupForm> => {
|
|
116
116
|
const errs = List<string>([])
|
|
117
117
|
.concat(s.email.includes("@") ? List([]) : List(["email must contain @"]))
|
|
118
|
-
.concat(s.age >= 18
|
|
118
|
+
.concat(s.age >= 18 ? List([]) : List(["age must be 18+"]))
|
|
119
119
|
return errs.isEmpty ? valid(s) : invalid(errs)
|
|
120
120
|
}
|
|
121
121
|
|
|
@@ -129,7 +129,9 @@ function Signup() {
|
|
|
129
129
|
<form onSubmit={form.handleSubmit(async (s) => api.signup(s))}>
|
|
130
130
|
<input value={form.values.email} onChange={(e) => form.setField("email", e.target.value)} />
|
|
131
131
|
<input type="number" value={form.values.age} onChange={(e) => form.setField("age", Number(e.target.value))} />
|
|
132
|
-
{form.errors.toArray().map((err, i) =>
|
|
132
|
+
{form.errors.toArray().map((err, i) => (
|
|
133
|
+
<p key={i}>{err}</p>
|
|
134
|
+
))}
|
|
133
135
|
<button disabled={!form.isValid}>sign up</button>
|
|
134
136
|
</form>
|
|
135
137
|
)
|
|
@@ -144,7 +146,7 @@ Errors accumulate applicatively — every failing rule is surfaced in one pass,
|
|
|
144
146
|
|
|
145
147
|
`functype-react/query` owns that bridge. Failures arrive boxed as `IOQueryError<E>`: a real `Error` with a populated `.message`, whose `.error` is still the fully discriminable functype error. Its `.name` is the cause's `_tag`, or a `TypedError`'s code (`NOT_FOUND`), so an error tracker groups by cause and can drop expected failures by name. A defect or an untagged cause keeps the name `IOQueryError`. Use `instanceof IOQueryError` or `isIOQueryError`, not `.name`, to recognize the box.
|
|
146
148
|
|
|
147
|
-
```
|
|
149
|
+
```tsx ignore
|
|
148
150
|
import { useIOQuery } from "functype-react/query"
|
|
149
151
|
import { Http, HttpErrors, type HttpError } from "functype/fetch"
|
|
150
152
|
|
|
@@ -170,7 +172,7 @@ if (error) {
|
|
|
170
172
|
|
|
171
173
|
The result above is still React Query's — `data` is `A | undefined`, so the success path needs a `!` or a guard. `toQueryState` projects it onto the same `AsyncState` ADT that `functype-react/async` returns, so a query matches exhaustively like any other functype value:
|
|
172
174
|
|
|
173
|
-
```tsx
|
|
175
|
+
```tsx ignore
|
|
174
176
|
import { Match } from "functype-react"
|
|
175
177
|
import { toQueryState, useIOQuery } from "functype-react/query"
|
|
176
178
|
|
|
@@ -196,7 +198,7 @@ The projection is a pure function over the result, so you keep everything else R
|
|
|
196
198
|
|
|
197
199
|
If the ADT is all you need, `useIOQueryState` skips the projection step — it returns `AsyncState` directly, plus the `isIdle`/`isPending`/`isSuccess`/`isFailure` flags and `refetch`, mirroring what `useIO` returns in Tier 3:
|
|
198
200
|
|
|
199
|
-
```tsx
|
|
201
|
+
```tsx ignore
|
|
200
202
|
const user = useIOQueryState(["user", id], ({ signal }) => Http.get<User>(url, { signal }))
|
|
201
203
|
|
|
202
204
|
<Match value={user}>
|
|
@@ -221,16 +223,21 @@ Two behaviours worth knowing before you rely on the ADT:
|
|
|
221
223
|
Mutations mirror the shape (React Query supplies no `AbortSignal` to mutations, so the callback takes only the variables):
|
|
222
224
|
|
|
223
225
|
```ts
|
|
226
|
+
import { Http } from "functype/fetch"
|
|
224
227
|
import { useIOMutation } from "functype-react/query"
|
|
225
228
|
|
|
226
229
|
const create = useIOMutation((body: CreateTokenInput) => Http.post<Token>(url, { headers, body }), {
|
|
227
|
-
onError: (e) => toast(e.message, { detail: e.error._tag }),
|
|
230
|
+
onError: (e) => toast(e.message, { detail: e.defect ? "unexpected" : e.error._tag }),
|
|
228
231
|
})
|
|
229
232
|
```
|
|
230
233
|
|
|
234
|
+
`e` is the `IOQueryError<E>` box, so the typed error is `e.error`, and only when `e.defect` is `false`. To branch on it as an `Option`, write `e.defect ? None<ApiError>() : Some(e.error)`, with your own error type in place of `ApiError`. A bare `None()` makes the result `Option<unknown>`.
|
|
235
|
+
|
|
231
236
|
For full control over the query object — or for `useSuspenseQuery` / `useInfiniteQuery` / `queryClient.prefetchQuery` — drop to the primitives. They carry no `@tanstack` types at all, so they compose with any of those:
|
|
232
237
|
|
|
233
|
-
```ts
|
|
238
|
+
```ts ignore
|
|
239
|
+
import { useQuery } from "@tanstack/react-query"
|
|
240
|
+
import { Http } from "functype/fetch"
|
|
234
241
|
import { ioQueryFn } from "functype-react/query"
|
|
235
242
|
|
|
236
243
|
useQuery({
|
|
@@ -242,7 +249,11 @@ useQuery({
|
|
|
242
249
|
|
|
243
250
|
`ioQueryFn` is generic over the query context, so a richer one flows through unchanged — annotate the callback parameter to reach `pageParam` in an infinite query:
|
|
244
251
|
|
|
245
|
-
```ts
|
|
252
|
+
```ts ignore
|
|
253
|
+
import { type QueryFunctionContext, type QueryKey, useInfiniteQuery } from "@tanstack/react-query"
|
|
254
|
+
import { Http } from "functype/fetch"
|
|
255
|
+
import { ioQueryFn } from "functype-react/query"
|
|
256
|
+
|
|
246
257
|
useInfiniteQuery({
|
|
247
258
|
queryKey: ["events"],
|
|
248
259
|
queryFn: ioQueryFn(({ signal, pageParam }: QueryFunctionContext<QueryKey, number>) =>
|
|
@@ -271,7 +282,7 @@ Both the hooks and the primitives are generic over any `IO<never, E, A>` — not
|
|
|
271
282
|
|
|
272
283
|
Both are `error` in `functype.configs.recommended`, the plugin's one preset.
|
|
273
284
|
|
|
274
|
-
They work without type information and are more precise with it (`parserOptions.projectService`). See the [plugin README](
|
|
285
|
+
They work without type information and are more precise with it (`parserOptions.projectService`). See the [plugin README](https://functype.org/eslint/#react-rules) for what each one reports.
|
|
275
286
|
|
|
276
287
|
## Deferred to v0.2
|
|
277
288
|
|
|
@@ -281,4 +292,4 @@ They work without type information and are more precise with it (`parserOptions.
|
|
|
281
292
|
|
|
282
293
|
## License
|
|
283
294
|
|
|
284
|
-
MIT — see [LICENSE](
|
|
295
|
+
MIT — see [LICENSE](https://github.com/jordanburke/functype/blob/main/LICENSE).
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lifecycle state of an async operation managed by `useIO` (and the query hooks'
|
|
3
|
+
* `toQueryState` / `useIOQueryState` projections).
|
|
4
|
+
*
|
|
5
|
+
* `Idle` is before the first run, `Pending` while it's in flight, then `Success` or
|
|
6
|
+
* `Failure`. A cancelled run (unmount, or `deps` changing) never reaches `Failure`: its
|
|
7
|
+
* result is discarded.
|
|
8
|
+
*/
|
|
9
|
+
type AsyncState<E, A> = {
|
|
10
|
+
readonly _tag: "Idle";
|
|
11
|
+
} | {
|
|
12
|
+
readonly _tag: "Pending";
|
|
13
|
+
} | {
|
|
14
|
+
readonly _tag: "Success";
|
|
15
|
+
readonly value: A;
|
|
16
|
+
} | {
|
|
17
|
+
readonly _tag: "Failure";
|
|
18
|
+
readonly error: E;
|
|
19
|
+
};
|
|
20
|
+
/** The `is…` flags for one case of `AsyncState`: `true` for that case, `false` for the rest. */
|
|
21
|
+
type FlagsFor<Tag extends AsyncState<unknown, unknown>["_tag"]> = {
|
|
22
|
+
readonly isIdle: Tag extends "Idle" ? true : false;
|
|
23
|
+
readonly isPending: Tag extends "Pending" ? true : false;
|
|
24
|
+
readonly isSuccess: Tag extends "Success" ? true : false;
|
|
25
|
+
readonly isFailure: Tag extends "Failure" ? true : false;
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* `AsyncState` with an `is…` flag for each case. Each flag is the literal `true` on its own case
|
|
29
|
+
* and `false` on the others, so a flag narrows the state the way `_tag` does:
|
|
30
|
+
* `if (state.isFailure) state.error` type-checks.
|
|
31
|
+
*/
|
|
32
|
+
type AsyncStateWithFlags<E, A> = ({
|
|
33
|
+
readonly _tag: "Idle";
|
|
34
|
+
} & FlagsFor<"Idle">) | ({
|
|
35
|
+
readonly _tag: "Pending";
|
|
36
|
+
} & FlagsFor<"Pending">) | ({
|
|
37
|
+
readonly _tag: "Success";
|
|
38
|
+
readonly value: A;
|
|
39
|
+
} & FlagsFor<"Success">) | ({
|
|
40
|
+
readonly _tag: "Failure";
|
|
41
|
+
readonly error: E;
|
|
42
|
+
} & FlagsFor<"Failure">);
|
|
43
|
+
/** Adds the `is…` flags to an `AsyncState`, typed per case so each flag narrows. */
|
|
44
|
+
declare const withFlags: <E, A>(state: AsyncState<E, A>) => AsyncStateWithFlags<E, A>;
|
|
45
|
+
export { AsyncStateWithFlags as n, withFlags as r, AsyncState as t };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as AsyncState } from "../AsyncState-
|
|
2
|
-
export { AsyncState };
|
|
1
|
+
import { n as AsyncStateWithFlags, r as withFlags, t as AsyncState } from "../AsyncState-CwxtGl5L.js";
|
|
2
|
+
export { AsyncState, AsyncStateWithFlags, withFlags };
|
package/dist/async/AsyncState.js
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
export{};
|
|
1
|
+
const e={isIdle:!1,isPending:!1,isSuccess:!1,isFailure:!1},t=t=>{switch(t._tag){case`Idle`:return{...t,...e,isIdle:!0};case`Pending`:return{...t,...e,isPending:!0};case`Success`:return{...t,...e,isSuccess:!0};case`Failure`:return{...t,...e,isFailure:!0}}};export{t as withFlags};
|
|
2
|
+
//# sourceMappingURL=AsyncState.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"AsyncState.js","names":["NONE","withFlags","state"],"sources":["../../src/async/AsyncState.ts"],"sourcesContent":["/**\n * Lifecycle state of an async operation managed by `useIO` (and the query hooks'\n * `toQueryState` / `useIOQueryState` projections).\n *\n * `Idle` is before the first run, `Pending` while it's in flight, then `Success` or\n * `Failure`. A cancelled run (unmount, or `deps` changing) never reaches `Failure`: its\n * result is discarded.\n */\nexport type AsyncState<E, A> =\n | { readonly _tag: \"Idle\" }\n | { readonly _tag: \"Pending\" }\n | { readonly _tag: \"Success\"; readonly value: A }\n | { readonly _tag: \"Failure\"; readonly error: E }\n\n/** The `is…` flags for one case of `AsyncState`: `true` for that case, `false` for the rest. */\ntype FlagsFor<Tag extends AsyncState<unknown, unknown>[\"_tag\"]> = {\n readonly isIdle: Tag extends \"Idle\" ? true : false\n readonly isPending: Tag extends \"Pending\" ? true : false\n readonly isSuccess: Tag extends \"Success\" ? true : false\n readonly isFailure: Tag extends \"Failure\" ? true : false\n}\n\n/**\n * `AsyncState` with an `is…` flag for each case. Each flag is the literal `true` on its own case\n * and `false` on the others, so a flag narrows the state the way `_tag` does:\n * `if (state.isFailure) state.error` type-checks.\n */\nexport type AsyncStateWithFlags<E, A> =\n | ({ readonly _tag: \"Idle\" } & FlagsFor<\"Idle\">)\n | ({ readonly _tag: \"Pending\" } & FlagsFor<\"Pending\">)\n | ({ readonly _tag: \"Success\"; readonly value: A } & FlagsFor<\"Success\">)\n | ({ readonly _tag: \"Failure\"; readonly error: E } & FlagsFor<\"Failure\">)\n\nconst NONE = { isIdle: false, isPending: false, isSuccess: false, isFailure: false } as const\n\n/** Adds the `is…` flags to an `AsyncState`, typed per case so each flag narrows. */\nexport const withFlags = <E, A>(state: AsyncState<E, A>): AsyncStateWithFlags<E, A> => {\n switch (state._tag) {\n case \"Idle\":\n return { ...state, ...NONE, isIdle: true }\n case \"Pending\":\n return { ...state, ...NONE, isPending: true }\n case \"Success\":\n return { ...state, ...NONE, isSuccess: true }\n case \"Failure\":\n return { ...state, ...NONE, isFailure: true }\n }\n}\n"],"mappings":"AAiCA,MAAMA,EAAO,CAAE,OAAQ,GAAO,UAAW,GAAO,UAAW,GAAO,UAAW,EAAM,EAGtEC,EAAmBC,GAAuD,CACrF,OAAQA,EAAM,KAAd,CACE,IAAK,OACH,MAAO,CAAE,GAAGA,EAAO,GAAGF,EAAM,OAAQ,EAAK,EAC3C,IAAK,UACH,MAAO,CAAE,GAAGE,EAAO,GAAGF,EAAM,UAAW,EAAK,EAC9C,IAAK,UACH,MAAO,CAAE,GAAGE,EAAO,GAAGF,EAAM,UAAW,EAAK,EAC9C,IAAK,UACH,MAAO,CAAE,GAAGE,EAAO,GAAGF,EAAM,UAAW,EAAK,CAChD,CACF,E"}
|
package/dist/async/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { ReactElement, ReactNode } from "react";
|
|
2
|
-
import { t as AsyncState } from "../AsyncState-
|
|
2
|
+
import { t as AsyncState } from "../AsyncState-CwxtGl5L.js";
|
|
3
3
|
import { UseIOResult, useIO } from "./useIO.js";
|
|
4
4
|
import { useIOPromise } from "./useIOPromise.js";
|
|
5
5
|
import { useIOValue } from "./useIOValue.js";
|
package/dist/async/useIO.d.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { IO } from "functype/io";
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
2
|
+
import { n as AsyncStateWithFlags } from "../AsyncState-CwxtGl5L.js";
|
|
3
|
+
/**
|
|
4
|
+
* `AsyncState` with its `is…` flags and a `refetch` trigger. Each flag narrows the state, so
|
|
5
|
+
* `if (state.isFailure)` makes `state.error` available, the same as checking `_tag`.
|
|
6
|
+
*/
|
|
7
|
+
export type UseIOResult<E, A> = AsyncStateWithFlags<E, A> & {
|
|
8
8
|
refetch: () => void;
|
|
9
9
|
};
|
|
10
10
|
/**
|
package/dist/async/useIO.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use client";import{Try as e}from"functype";import{useCallback as t,useEffect as n,useReducer as r,useRef as i,useState as a}from"react";function
|
|
1
|
+
"use client";import{Try as e}from"functype";import{useCallback as t,useEffect as n,useReducer as r,useRef as i,useState as a}from"react";import{withFlags as o}from"./AsyncState.js";function s(e,t){return t.type===`PENDING`?{_tag:`Pending`}:t.type===`SUCCESS`?{_tag:`Success`,value:t.value}:{_tag:`Failure`,error:t.error}}function c(c,l){let[u,d]=r(s,{_tag:`Idle`}),[f,p]=a(void 0),[m,h]=r(e=>e+1,0),g=i(c);g.current=c,n(()=>{let t=new AbortController;d({type:`PENDING`});let n=e=>{t.signal.aborted||e.fold(e=>d({type:`FAILURE`,error:e}),e=>d({type:`SUCCESS`,value:e}),()=>p({value:/* @__PURE__ */ Error(`useIO: the effect interrupted itself`)}),e=>p({value:e}))};return e(()=>g.current(t.signal)).fold(e=>p({value:e}),e=>void e.runExit({signal:t.signal}).then(n)),()=>t.abort()},[...l,m]);let _=t(()=>h(),[]);if(f)throw f.value;return{...o(u),refetch:_}}export{c as useIO};
|
|
2
2
|
//# sourceMappingURL=useIO.js.map
|
package/dist/async/useIO.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useIO.js","names":["Try","useCallback","useEffect","useReducer","useRef","useState","reducer","_state","action","useIO","io","deps","state","dispatch","defect","setDefect","refetchTick","forceRefetch","n","ioRef","controller","settle","exit","error","value","thrown","effect","refetch"],"sources":["../../src/async/useIO.ts"],"sourcesContent":["\"use client\"\n\nimport { Try } from \"functype\"\nimport type { Exit, IO } from \"functype/io\"\nimport { useCallback, useEffect, useReducer, useRef, useState } from \"react\"\n\nimport type
|
|
1
|
+
{"version":3,"file":"useIO.js","names":["Try","useCallback","useEffect","useReducer","useRef","useState","withFlags","reducer","_state","action","useIO","io","deps","state","dispatch","defect","setDefect","refetchTick","forceRefetch","n","ioRef","controller","settle","exit","error","value","thrown","effect","refetch"],"sources":["../../src/async/useIO.ts"],"sourcesContent":["\"use client\"\n\nimport { Try } from \"functype\"\nimport type { Exit, IO } from \"functype/io\"\nimport { useCallback, useEffect, useReducer, useRef, useState } from \"react\"\n\nimport { type AsyncState, type AsyncStateWithFlags, withFlags } from \"./AsyncState\"\n\ntype Action<E, A> =\n | { readonly type: \"PENDING\" }\n | { readonly type: \"SUCCESS\"; readonly value: A }\n | { readonly type: \"FAILURE\"; readonly error: E }\n\nfunction reducer<E, A>(_state: AsyncState<E, A>, action: Action<E, A>): AsyncState<E, A> {\n if (action.type === \"PENDING\") return { _tag: \"Pending\" }\n if (action.type === \"SUCCESS\") return { _tag: \"Success\", value: action.value }\n return { _tag: \"Failure\", error: action.error }\n}\n\n/**\n * `AsyncState` with its `is…` flags and a `refetch` trigger. Each flag narrows the state, so\n * `if (state.isFailure)` makes `state.error` available, the same as checking `_tag`.\n */\nexport type UseIOResult<E, A> = AsyncStateWithFlags<E, A> & {\n refetch: () => void\n}\n\n/**\n * Runs an `IO<never, E, A>` tied to a component's lifecycle and returns its `AsyncState`,\n * plus boolean flags and a `refetch` trigger.\n *\n * - The factory receives an `AbortSignal` that aborts on unmount or when `deps` change.\n * The effect is cancelled with it: no further step runs once it fires. Also pass it to\n * `Http` / `IO.tryAsync` so an in-flight request aborts too.\n * - A cancelled run's result is discarded, so it never shows up as `Failure`.\n * - A typed failure becomes `Failure` with the effect's `E`.\n * - A defect (a bug: a throw inside the effect, or the factory throwing while building it)\n * is rethrown during render, so the nearest error boundary catches it, the way a bug in\n * any other component would surface.\n * - StrictMode-safe: the cleanup aborts the signal and discards any late result.\n *\n * @interop React reaches an error boundary only through a throw during render, so a defect is rethrown there.\n */\nexport function useIO<E, A>(\n io: (signal: AbortSignal) => IO<never, E, A>,\n deps: ReadonlyArray<unknown>,\n): UseIOResult<E, A> {\n const [state, dispatch] = useReducer(reducer<E, A>, { _tag: \"Idle\" })\n const [defect, setDefect] = useState<{ readonly value: unknown } | undefined>(undefined)\n const [refetchTick, forceRefetch] = useReducer((n: number) => n + 1, 0)\n const ioRef = useRef(io)\n ioRef.current = io\n\n useEffect(() => {\n const controller = new AbortController()\n dispatch({ type: \"PENDING\" })\n\n const settle = (exit: Exit<E, A>): void => {\n if (controller.signal.aborted) return\n exit.fold(\n (error) => dispatch({ type: \"FAILURE\", error }),\n (value) => dispatch({ type: \"SUCCESS\", value }),\n // Interrupted without an abort means the effect interrupted itself (IO.interrupt()):\n // there is no value and no E, so it is reported like a defect.\n () => setDefect({ value: new Error(\"useIO: the effect interrupted itself\") }),\n (defect) => setDefect({ value: defect }),\n )\n }\n\n // The factory is user code and can throw while building the effect; that's a defect too.\n Try(() => ioRef.current(controller.signal)).fold(\n (thrown) => setDefect({ value: thrown }),\n (effect) => void effect.runExit({ signal: controller.signal }).then(settle),\n )\n\n return () => controller.abort()\n }, [...deps, refetchTick])\n\n const refetch = useCallback(() => forceRefetch(), [])\n\n if (defect) throw defect.value\n\n return {\n ...withFlags(state),\n refetch,\n }\n}\n"],"mappings":"A,qLAaA,SAASO,EAAcC,EAA0BC,EAAwC,CAGvF,OAFIA,EAAO,OAAS,UAAkB,CAAE,KAAM,SAAU,EACpDA,EAAO,OAAS,UAAkB,CAAE,KAAM,UAAW,MAAOA,EAAO,KAAM,EACtE,CAAE,KAAM,UAAW,MAAOA,EAAO,KAAM,CAChD,CA0BA,SAAgBC,EACdC,EACAC,EACmB,CACnB,GAAM,CAACC,EAAOC,GAAYX,EAAWI,EAAe,CAAE,KAAM,MAAO,CAAC,EAC9D,CAACQ,EAAQC,GAAaX,EAAkD,IAAA,EAAS,EACjF,CAACY,EAAaC,GAAgBf,EAAYgB,GAAcA,EAAI,EAAG,CAAC,EAChEC,EAAQhB,EAAOO,CAAE,EACvBS,EAAM,QAAUT,EAEhBT,MAAgB,CACd,IAAMmB,EAAa,IAAI,gBACvBP,EAAS,CAAE,KAAM,SAAU,CAAC,EAE5B,IAAMQ,EAAUC,GAA2B,CACrCF,EAAW,OAAO,SACtBE,EAAK,KACFC,GAAUV,EAAS,CAAE,KAAM,UAAWU,OAAM,CAAC,EAC7CC,GAAUX,EAAS,CAAE,KAAM,UAAWW,OAAM,CAAC,MAGxCT,EAAU,CAAE,MAAO,gBAAI,MAAM,sCAAsC,CAAE,CAAC,EAC3ED,GAAWC,EAAU,CAAE,MAAOD,CAAO,CAAC,CACzC,CACF,EAQA,OALAf,MAAUoB,EAAM,QAAQC,EAAW,MAAM,CAAC,CAAC,CAAC,KACzCK,GAAWV,EAAU,CAAE,MAAOU,CAAO,CAAC,EACtCC,GAAW,KAAKA,EAAO,QAAQ,CAAE,OAAQN,EAAW,MAAO,CAAC,CAAC,CAAC,KAAKC,CAAM,CAC5E,MAEaD,EAAW,MAAM,CAChC,EAAG,CAAC,GAAGT,EAAMK,CAAW,CAAC,EAEzB,IAAMW,EAAU3B,MAAkBiB,EAAa,EAAG,CAAC,CAAC,EAEpD,GAAIH,EAAQ,MAAMA,EAAO,MAEzB,MAAO,CACL,GAAGT,EAAUO,CAAK,EAClBe,SACF,CACF,C"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as AsyncState } from "../AsyncState-
|
|
1
|
+
import { t as AsyncState } from "../AsyncState-CwxtGl5L.js";
|
|
2
2
|
/**
|
|
3
3
|
* Structural view of a React Query result — the discriminated shape this module
|
|
4
4
|
* actually depends on. Typed structurally (like {@link IOQueryFnContext}) so the
|
|
@@ -11,7 +11,7 @@ export type UseIOMutationOptions<A, E, V, TContext> = Omit<UseMutationOptions<A,
|
|
|
11
11
|
*
|
|
12
12
|
* ```ts
|
|
13
13
|
* const create = useIOMutation((body: CreateTokenInput) => Http.post<Token>(url, { headers, body }), {
|
|
14
|
-
* onError: (e) => toast(e.message, { detail: e.error._tag }),
|
|
14
|
+
* onError: (e) => toast(e.message, { detail: e.defect ? "unexpected" : e.error._tag }),
|
|
15
15
|
* })
|
|
16
16
|
*
|
|
17
17
|
* create.mutate({ name: "ci" })
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useIOMutation.js","names":["useMutation","ioMutationFn","useIOMutation","io","options","formatError","mutationOptions"],"sources":["../../src/query/useIOMutation.ts"],"sourcesContent":["\"use client\"\n\nimport type { UseMutationOptions, UseMutationResult } from \"@tanstack/react-query\"\nimport { useMutation } from \"@tanstack/react-query\"\nimport type { IO } from \"functype/io\"\n\nimport type { IOQueryError } from \"./IOQueryError\"\nimport { ioMutationFn } from \"./ioQueryFn\"\n\nexport type UseIOMutationOptions<A, E, V, TContext> = Omit<\n UseMutationOptions<A, IOQueryError<E>, V, TContext>,\n \"mutationFn\"\n> & {\n /** Override the derived `Error.message` on failure. */\n readonly formatError?: (error: E) => string\n}\n\n/**\n * `useMutation` for effects — runs an `IO<never, E, A>` per invocation and threads its\n * typed error channel through to React Query.\n *\n * ```ts\n * const create = useIOMutation((body: CreateTokenInput) => Http.post<Token>(url, { headers, body }), {\n * onError: (e) => toast(e.message, { detail: e.error._tag }),\n * })\n *\n * create.mutate({ name: \"ci\" })\n * ```\n *\n * React Query does not supply an `AbortSignal` to mutations, so the callback receives\n * only the mutation variables.\n */\nexport function useIOMutation<A, E, V = void, TContext = unknown>(\n io: (variables: V) => IO<never, E, A>,\n options?: UseIOMutationOptions<A, E, V, TContext>,\n): UseMutationResult<A, IOQueryError<E>, V, TContext> {\n const { formatError, ...mutationOptions } = options ?? {}\n\n return useMutation<A, IOQueryError<E>, V, TContext>({\n ...mutationOptions,\n mutationFn: ioMutationFn<E, A, V>(io, { formatError }),\n })\n}\n"],"mappings":"A,+GAgCA,SAAgBE,EACdC,EACAC,EACoD,CACpD,GAAM,CAAEC,cAAa,GAAGC,GAAoBF,GAAW,CAAC,EAExD,OAAOJ,EAA6C,CAClD,GAAGM,EACH,WAAYL,EAAsBE,EAAI,CAAEE,aAAY,CAAC,CACvD,CAAC,CACH,C"}
|
|
1
|
+
{"version":3,"file":"useIOMutation.js","names":["useMutation","ioMutationFn","useIOMutation","io","options","formatError","mutationOptions"],"sources":["../../src/query/useIOMutation.ts"],"sourcesContent":["\"use client\"\n\nimport type { UseMutationOptions, UseMutationResult } from \"@tanstack/react-query\"\nimport { useMutation } from \"@tanstack/react-query\"\nimport type { IO } from \"functype/io\"\n\nimport type { IOQueryError } from \"./IOQueryError\"\nimport { ioMutationFn } from \"./ioQueryFn\"\n\nexport type UseIOMutationOptions<A, E, V, TContext> = Omit<\n UseMutationOptions<A, IOQueryError<E>, V, TContext>,\n \"mutationFn\"\n> & {\n /** Override the derived `Error.message` on failure. */\n readonly formatError?: (error: E) => string\n}\n\n/**\n * `useMutation` for effects — runs an `IO<never, E, A>` per invocation and threads its\n * typed error channel through to React Query.\n *\n * ```ts\n * const create = useIOMutation((body: CreateTokenInput) => Http.post<Token>(url, { headers, body }), {\n * onError: (e) => toast(e.message, { detail: e.defect ? \"unexpected\" : e.error._tag }),\n * })\n *\n * create.mutate({ name: \"ci\" })\n * ```\n *\n * React Query does not supply an `AbortSignal` to mutations, so the callback receives\n * only the mutation variables.\n */\nexport function useIOMutation<A, E, V = void, TContext = unknown>(\n io: (variables: V) => IO<never, E, A>,\n options?: UseIOMutationOptions<A, E, V, TContext>,\n): UseMutationResult<A, IOQueryError<E>, V, TContext> {\n const { formatError, ...mutationOptions } = options ?? {}\n\n return useMutation<A, IOQueryError<E>, V, TContext>({\n ...mutationOptions,\n mutationFn: ioMutationFn<E, A, V>(io, { formatError }),\n })\n}\n"],"mappings":"A,+GAgCA,SAAgBE,EACdC,EACAC,EACoD,CACpD,GAAM,CAAEC,cAAa,GAAGC,GAAoBF,GAAW,CAAC,EAExD,OAAOJ,EAA6C,CAClD,GAAGM,EACH,WAAYL,EAAsBE,EAAI,CAAEE,aAAY,CAAC,CACvD,CAAC,CACH,C"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { UseMutationResult } from "@tanstack/react-query";
|
|
2
2
|
import { IO } from "functype/io";
|
|
3
|
-
import {
|
|
3
|
+
import { n as AsyncStateWithFlags } from "../AsyncState-CwxtGl5L.js";
|
|
4
4
|
import { IOQueryError } from "./IOQueryError.js";
|
|
5
5
|
import { UseIOMutationOptions } from "./useIOMutation.js";
|
|
6
6
|
/**
|
|
@@ -8,12 +8,7 @@ import { UseIOMutationOptions } from "./useIOMutation.js";
|
|
|
8
8
|
* useless without its trigger, so `mutate` / `mutateAsync` / `reset` are carried
|
|
9
9
|
* through with React Query's own signatures.
|
|
10
10
|
*/
|
|
11
|
-
export type UseIOMutationStateResult<A, E, V, TContext> =
|
|
12
|
-
readonly isIdle: boolean;
|
|
13
|
-
readonly isPending: boolean;
|
|
14
|
-
readonly isSuccess: boolean;
|
|
15
|
-
readonly isFailure: boolean;
|
|
16
|
-
};
|
|
11
|
+
export type UseIOMutationStateResult<A, E, V, TContext> = AsyncStateWithFlags<IOQueryError<E>, A> & Pick<UseMutationResult<A, IOQueryError<E>, V, TContext>, "mutate" | "mutateAsync" | "reset">;
|
|
17
12
|
/**
|
|
18
13
|
* `useIOMutation` projected onto the `AsyncState` ADT, so a mutation's lifecycle matches
|
|
19
14
|
* exhaustively like a query's. React Query's own `idle` status maps directly onto `Idle`.
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use client";import{
|
|
1
|
+
"use client";import{withFlags as e}from"../async/AsyncState.js";import{toMutationState as t}from"./queryState.js";import{useIOMutation as n}from"./useIOMutation.js";function r(r,i){let a=n(r,i),o=t(a);return{...e(o),mutate:a.mutate,mutateAsync:a.mutateAsync,reset:a.reset}}export{r as useIOMutationState};
|
|
2
2
|
//# sourceMappingURL=useIOMutationState.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useIOMutationState.js","names":["toMutationState","useIOMutation","useIOMutationState","io","options","mutation","state"],"sources":["../../src/query/useIOMutationState.ts"],"sourcesContent":["\"use client\"\n\nimport type { UseMutationResult } from \"@tanstack/react-query\"\nimport type { IO } from \"functype/io\"\n\nimport type
|
|
1
|
+
{"version":3,"file":"useIOMutationState.js","names":["withFlags","toMutationState","useIOMutation","useIOMutationState","io","options","mutation","state"],"sources":["../../src/query/useIOMutationState.ts"],"sourcesContent":["\"use client\"\n\nimport type { UseMutationResult } from \"@tanstack/react-query\"\nimport type { IO } from \"functype/io\"\n\nimport { type AsyncStateWithFlags, withFlags } from \"../async/AsyncState\"\nimport type { IOQueryError } from \"./IOQueryError\"\nimport { toMutationState } from \"./queryState\"\nimport type { UseIOMutationOptions } from \"./useIOMutation\"\nimport { useIOMutation } from \"./useIOMutation\"\n\n/**\n * `AsyncState` plus the flags and the trigger functions. Unlike a query, a mutation is\n * useless without its trigger, so `mutate` / `mutateAsync` / `reset` are carried\n * through with React Query's own signatures.\n */\nexport type UseIOMutationStateResult<A, E, V, TContext> = AsyncStateWithFlags<IOQueryError<E>, A> &\n Pick<UseMutationResult<A, IOQueryError<E>, V, TContext>, \"mutate\" | \"mutateAsync\" | \"reset\">\n\n/**\n * `useIOMutation` projected onto the `AsyncState` ADT, so a mutation's lifecycle matches\n * exhaustively like a query's. React Query's own `idle` status maps directly onto `Idle`.\n *\n * ```tsx\n * const create = useIOMutationState((body: CreateTokenInput) => Http.post<Token>(url, { body }))\n *\n * <button onClick={() => create.mutate({ name: \"ci\" })} disabled={create.isPending}>create</button>\n *\n * <Match value={create}>\n * {{\n * Idle: () => null,\n * Pending: () => <Spinner />,\n * Failure: ({ error }) => <Err e={error.error} />,\n * Success: ({ value }) => <TokenRow token={value} />,\n * }}\n * </Match>\n * ```\n */\nexport function useIOMutationState<A, E, V = void, TContext = unknown>(\n io: (variables: V) => IO<never, E, A>,\n options?: UseIOMutationOptions<A, E, V, TContext>,\n): UseIOMutationStateResult<A, E, V, TContext> {\n const mutation = useIOMutation(io, options)\n const state = toMutationState(mutation)\n\n return {\n ...withFlags(state),\n mutate: mutation.mutate,\n mutateAsync: mutation.mutateAsync,\n reset: mutation.reset,\n }\n}\n"],"mappings":"A,qKAsCA,SAAgBG,EACdC,EACAC,EAC6C,CAC7C,IAAMC,EAAWJ,EAAcE,EAAIC,CAAO,EACpCE,EAAQN,EAAgBK,CAAQ,EAEtC,MAAO,CACL,GAAGN,EAAUO,CAAK,EAClB,OAAQD,EAAS,OACjB,YAAaA,EAAS,YACtB,MAAOA,EAAS,KAClB,CACF,C"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { QueryFunctionContext, QueryKey, UseQueryResult } from "@tanstack/react-query";
|
|
2
2
|
import { IO } from "functype/io";
|
|
3
|
-
import {
|
|
3
|
+
import { n as AsyncStateWithFlags } from "../AsyncState-CwxtGl5L.js";
|
|
4
4
|
import { IOQueryError } from "./IOQueryError.js";
|
|
5
5
|
import { UseIOQueryOptions } from "./useIOQuery.js";
|
|
6
6
|
/**
|
|
@@ -9,12 +9,7 @@ import { UseIOQueryOptions } from "./useIOQuery.js";
|
|
|
9
9
|
*
|
|
10
10
|
* `refetch` keeps React Query's own signature rather than a lossy re-declaration.
|
|
11
11
|
*/
|
|
12
|
-
export type UseIOQueryStateResult<A, E> =
|
|
13
|
-
readonly isIdle: boolean;
|
|
14
|
-
readonly isPending: boolean;
|
|
15
|
-
readonly isSuccess: boolean;
|
|
16
|
-
readonly isFailure: boolean;
|
|
17
|
-
};
|
|
12
|
+
export type UseIOQueryStateResult<A, E> = AsyncStateWithFlags<IOQueryError<E>, A> & Pick<UseQueryResult<A, IOQueryError<E>>, "refetch">;
|
|
18
13
|
/**
|
|
19
14
|
* `useIOQuery` projected straight onto the `AsyncState` ADT — the flag-soup-free path
|
|
20
15
|
* in one call.
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use client";import{
|
|
1
|
+
"use client";import{withFlags as e}from"../async/AsyncState.js";import{toQueryState as t}from"./queryState.js";import{useIOQuery as n}from"./useIOQuery.js";function r(r,i,a){let o=n(r,i,a),s=t(o);return{...e(s),refetch:o.refetch}}export{r as useIOQueryState};
|
|
2
2
|
//# sourceMappingURL=useIOQueryState.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useIOQueryState.js","names":["toQueryState","useIOQuery","useIOQueryState","queryKey","io","options","query","state"],"sources":["../../src/query/useIOQueryState.ts"],"sourcesContent":["\"use client\"\n\nimport type { QueryFunctionContext, QueryKey, UseQueryResult } from \"@tanstack/react-query\"\nimport type { IO } from \"functype/io\"\n\nimport type
|
|
1
|
+
{"version":3,"file":"useIOQueryState.js","names":["withFlags","toQueryState","useIOQuery","useIOQueryState","queryKey","io","options","query","state"],"sources":["../../src/query/useIOQueryState.ts"],"sourcesContent":["\"use client\"\n\nimport type { QueryFunctionContext, QueryKey, UseQueryResult } from \"@tanstack/react-query\"\nimport type { IO } from \"functype/io\"\n\nimport { type AsyncStateWithFlags, withFlags } from \"../async/AsyncState\"\nimport type { IOQueryError } from \"./IOQueryError\"\nimport { toQueryState } from \"./queryState\"\nimport type { UseIOQueryOptions } from \"./useIOQuery\"\nimport { useIOQuery } from \"./useIOQuery\"\n\n/**\n * `AsyncState` plus the convenience flags and refetch trigger, mirroring\n * `UseIOResult` from `functype-react/async` so both async surfaces read alike.\n *\n * `refetch` keeps React Query's own signature rather than a lossy re-declaration.\n */\nexport type UseIOQueryStateResult<A, E> = AsyncStateWithFlags<IOQueryError<E>, A> &\n Pick<UseQueryResult<A, IOQueryError<E>>, \"refetch\">\n\n/**\n * `useIOQuery` projected straight onto the `AsyncState` ADT — the flag-soup-free path\n * in one call.\n *\n * ```tsx\n * const user = useIOQueryState([\"user\", id], ({ signal }) => Http.get<User>(url, { signal }))\n *\n * <Match value={user}>\n * {{\n * Idle: () => null,\n * Pending: () => <Spinner />,\n * Failure: ({ error }) => <Err e={error.error} />,\n * Success: ({ value }) => <Profile user={value} />,\n * }}\n * </Match>\n * ```\n *\n * Reads only `status` / `fetchStatus` / `data` / `error` / `refetch` off the query, so\n * React Query's tracked-properties optimization still applies — the component is not\n * subscribed to fields it never renders. When you need the rest of the result\n * (`isFetching`, `dataUpdatedAt`, `failureCount`), use {@link useIOQuery} with\n * {@link toQueryState} instead.\n */\nexport function useIOQueryState<A, E, TData = A, TQueryKey extends QueryKey = QueryKey>(\n queryKey: TQueryKey,\n io: (context: QueryFunctionContext<TQueryKey>) => IO<never, E, A>,\n options?: UseIOQueryOptions<A, E, TData, TQueryKey>,\n): UseIOQueryStateResult<TData, E> {\n const query = useIOQuery(queryKey, io, options)\n const state = toQueryState(query)\n\n return {\n ...withFlags(state),\n refetch: query.refetch,\n }\n}\n"],"mappings":"A,4JA2CA,SAAgBG,EACdC,EACAC,EACAC,EACiC,CACjC,IAAMC,EAAQL,EAAWE,EAAUC,EAAIC,CAAO,EACxCE,EAAQP,EAAaM,CAAK,EAEhC,MAAO,CACL,GAAGP,EAAUQ,CAAK,EAClB,QAASD,EAAM,OACjB,CACF,C"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "functype-react",
|
|
3
|
-
"version": "2.2.
|
|
3
|
+
"version": "2.2.2",
|
|
4
4
|
"description": "React bindings for functype — ADT-aware hooks and exhaustive pattern matching components",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"functype",
|
|
@@ -47,7 +47,7 @@
|
|
|
47
47
|
"@types/react": "^19.3.0",
|
|
48
48
|
"@types/react-dom": "^19.3.0",
|
|
49
49
|
"fast-check": "^4.10.3",
|
|
50
|
-
"functype": "^2.2.
|
|
50
|
+
"functype": "^2.2.2",
|
|
51
51
|
"jsdom": "^31.0.1",
|
|
52
52
|
"react": "^19.3.1",
|
|
53
53
|
"react-dom": "^19.3.1",
|
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Lifecycle state of an async operation managed by `useIO` (and the query hooks'
|
|
3
|
-
* `toQueryState` / `useIOQueryState` projections).
|
|
4
|
-
*
|
|
5
|
-
* `Idle` is before the first run, `Pending` while it's in flight, then `Success` or
|
|
6
|
-
* `Failure`. A cancelled run (unmount, or `deps` changing) never reaches `Failure`: its
|
|
7
|
-
* result is discarded.
|
|
8
|
-
*/
|
|
9
|
-
type AsyncState<E, A> = {
|
|
10
|
-
readonly _tag: "Idle";
|
|
11
|
-
} | {
|
|
12
|
-
readonly _tag: "Pending";
|
|
13
|
-
} | {
|
|
14
|
-
readonly _tag: "Success";
|
|
15
|
-
readonly value: A;
|
|
16
|
-
} | {
|
|
17
|
-
readonly _tag: "Failure";
|
|
18
|
-
readonly error: E;
|
|
19
|
-
};
|
|
20
|
-
export { AsyncState as t };
|