@softistx/riva-react 0.0.0-stage → 0.1.0

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.
Files changed (52) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +220 -2
  3. package/dist/chunks/index-gzs9smr9.js +42 -0
  4. package/dist/chunks/index-gzs9smr9.js.map +10 -0
  5. package/dist/chunks/index-zww0a7j9.js +20 -0
  6. package/dist/chunks/index-zww0a7j9.js.map +10 -0
  7. package/dist/context.d.ts +12 -0
  8. package/dist/context.d.ts.map +1 -0
  9. package/dist/entities/index.d.ts +2 -0
  10. package/dist/entities/index.d.ts.map +1 -0
  11. package/dist/entities/index.js +21 -0
  12. package/dist/entities/index.js.map +10 -0
  13. package/dist/entities/use-fragment.d.ts +7 -0
  14. package/dist/entities/use-fragment.d.ts.map +1 -0
  15. package/dist/index.d.ts +5 -0
  16. package/dist/index.d.ts.map +1 -0
  17. package/dist/index.js +111 -0
  18. package/dist/index.js.map +13 -0
  19. package/dist/infinite/index.d.ts +2 -0
  20. package/dist/infinite/index.d.ts.map +1 -0
  21. package/dist/infinite/index.js +21 -0
  22. package/dist/infinite/index.js.map +10 -0
  23. package/dist/infinite/use-infinite-query.d.ts +19 -0
  24. package/dist/infinite/use-infinite-query.d.ts.map +1 -0
  25. package/dist/query-state.d.ts +18 -0
  26. package/dist/query-state.d.ts.map +1 -0
  27. package/dist/store/index.d.ts +2 -0
  28. package/dist/store/index.d.ts.map +1 -0
  29. package/dist/store/index.js +75 -0
  30. package/dist/store/index.js.map +10 -0
  31. package/dist/store/use-store.d.ts +12 -0
  32. package/dist/store/use-store.d.ts.map +1 -0
  33. package/dist/suspend.d.ts +8 -0
  34. package/dist/suspend.d.ts.map +1 -0
  35. package/dist/use-mutation.d.ts +18 -0
  36. package/dist/use-mutation.d.ts.map +1 -0
  37. package/dist/use-query.d.ts +25 -0
  38. package/dist/use-query.d.ts.map +1 -0
  39. package/dist/use-signal.d.ts +6 -0
  40. package/dist/use-signal.d.ts.map +1 -0
  41. package/docs/README.md +20 -0
  42. package/docs/guide/entities.md +25 -0
  43. package/docs/guide/infinite.md +35 -0
  44. package/docs/guide/mutations.md +41 -0
  45. package/docs/guide/provider.md +34 -0
  46. package/docs/guide/queries.md +41 -0
  47. package/docs/guide/signals.md +27 -0
  48. package/docs/guide/ssr.md +27 -0
  49. package/docs/guide/store.md +27 -0
  50. package/docs/guide/suspense.md +38 -0
  51. package/docs/troubleshooting.md +102 -0
  52. package/package.json +82 -5
@@ -0,0 +1,18 @@
1
+ import { type Query, type QueryState, type RivaClient } from '@softistx/riva';
2
+ export type AnyQuery = Query<any, any, any>;
3
+ /** The variables of the first render that produced this key: an inline `{ a }` never resubscribes. */
4
+ export declare function useStableVars<V>(id: string, vars: V): {
5
+ key: string;
6
+ vars: V;
7
+ };
8
+ export interface QueryBinding<S> {
9
+ client: RivaClient;
10
+ state: S;
11
+ key: string;
12
+ vars: unknown;
13
+ /** Marks the entry stale and fetches it; never rejects, the error is in the state. */
14
+ refetch: () => Promise<void>;
15
+ }
16
+ /** Observes a query entry through `useSyncExternalStore`; nothing is observed while disabled. */
17
+ export declare function useQueryState<S extends QueryState<unknown>>(def: AnyQuery, vars: unknown, enabled: boolean, suspense?: boolean): QueryBinding<S>;
18
+ //# sourceMappingURL=query-state.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"query-state.d.ts","sourceRoot":"","sources":["../src/query-state.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,KAAK,EACV,KAAK,UAAU,EACf,KAAK,UAAU,EAEf,MAAM,gBAAgB,CAAC;AAKxB,MAAM,MAAM,QAAQ,GAAG,KAAK,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC;AAgB5C,sGAAsG;AACtG,wBAAgB,aAAa,CAAC,CAAC,EAC9B,EAAE,EAAE,MAAM,EACV,IAAI,EAAE,CAAC,GACL;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,CAAC,CAAA;CAAE,CAK1B;AAED,MAAM,WAAW,YAAY,CAAC,CAAC;IAC9B,MAAM,EAAE,UAAU,CAAC;IACnB,KAAK,EAAE,CAAC,CAAC;IACT,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,OAAO,CAAC;IACd,sFAAsF;IACtF,OAAO,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CAC7B;AAED,iGAAiG;AACjG,wBAAgB,aAAa,CAAC,CAAC,SAAS,UAAU,CAAC,OAAO,CAAC,EAC1D,GAAG,EAAE,QAAQ,EACb,IAAI,EAAE,OAAO,EACb,OAAO,EAAE,OAAO,EAChB,QAAQ,UAAQ,GACd,YAAY,CAAC,CAAC,CAAC,CAuBjB"}
@@ -0,0 +1,2 @@
1
+ export { useStore } from './use-store';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/store/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC"}
@@ -0,0 +1,75 @@
1
+ import {
2
+ useClient2
3
+ } from "../chunks/index-zww0a7j9.js";
4
+
5
+ // src/store/use-store.ts
6
+ import {
7
+ RivaError,
8
+ signal
9
+ } from "@softistx/riva";
10
+ import {
11
+ useCallback,
12
+ useLayoutEffect,
13
+ useMemo,
14
+ useSyncExternalStore
15
+ } from "react";
16
+ var isMember = (m) => m?.kind === "signal" || m?.kind === "computed";
17
+ function useStore(def) {
18
+ const client = useClient2();
19
+ const t = useMemo(() => ({
20
+ keys: new Set,
21
+ committed: [],
22
+ seen: new Map,
23
+ ver: 0,
24
+ tick: signal(0)
25
+ }), [client, def]);
26
+ const subscribe = useCallback((notify) => client.effect(() => {
27
+ client.get(t.tick);
28
+ let changed = false;
29
+ for (const m of t.committed) {
30
+ const v = client.get(m);
31
+ if (!Object.is(t.seen.get(m), v)) {
32
+ t.seen.set(m, v);
33
+ changed = true;
34
+ }
35
+ }
36
+ if (changed) {
37
+ t.ver++;
38
+ notify();
39
+ }
40
+ }), [client, t]);
41
+ const read = () => t.ver;
42
+ const ver = useSyncExternalStore(subscribe, read, read);
43
+ const a = def.bind(client)[1];
44
+ const s = useMemo(() => {
45
+ t.keys.clear();
46
+ return new Proxy({}, {
47
+ get: (_, k) => {
48
+ const m = def[k];
49
+ if (!isMember(m))
50
+ return;
51
+ const v = client.get(m);
52
+ t.keys.add(m);
53
+ t.seen.set(m, v);
54
+ return v;
55
+ },
56
+ set: (_, k) => {
57
+ throw new RivaError("RIVA_STORE", `Store "${def.name}": "${String(k)}" is read-only here; write it in an action.`);
58
+ }
59
+ });
60
+ }, [t, ver, a]);
61
+ useLayoutEffect(() => {
62
+ const next = [...t.keys];
63
+ if (next.length !== t.committed.length || next.some((m) => !t.committed.includes(m))) {
64
+ t.committed = next;
65
+ client.set(t.tick, (n) => n + 1);
66
+ }
67
+ });
68
+ return useMemo(() => [s, a], [s, a]);
69
+ }
70
+ export {
71
+ useStore
72
+ };
73
+
74
+ //# debugId=9C9767EA0A2D993664756E2164756E21
75
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,10 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/store/use-store.ts"],
4
+ "sourcesContent": [
5
+ "import {\n\ttype Readable,\n\ttype RivaClient,\n\tRivaError,\n\ttype Signal,\n\tsignal,\n} from '@softistx/riva';\nimport {\n\tuseCallback,\n\tuseLayoutEffect,\n\tuseMemo,\n\tuseSyncExternalStore,\n} from 'react';\nimport { useClient } from '../context';\n\ninterface Tracker {\n\t/** What the renders since the view was last built read: not committed yet. */\n\tkeys: Set<Readable<unknown>>;\n\t/** What the last committed render read: the keys the subscription watches. */\n\tcommitted: Readable<unknown>[];\n\t/** What the last render, or the last check, saw of each. */\n\tseen: Map<Readable<unknown>, unknown>;\n\tver: number;\n\t/** Bumped after a commit that read other keys, so the subscription follows. */\n\ttick: Signal<number>;\n}\n\nconst isMember = (m: unknown): m is Readable<unknown> =>\n\t(m as Readable<unknown> | undefined)?.kind === 'signal' ||\n\t(m as Readable<unknown> | undefined)?.kind === 'computed';\n\n/**\n * A store's state and computeds as `s`, and its actions as `a`, bound to the\n * provider's client. `s` is tracked per key: the component re-renders only\n * when a key it read changes, and `s` is a new object after each change, so\n * `useMemo([s])` and `React.memo` children follow it.\n */\nexport function useStore<V, B>(def: {\n\treadonly name: string;\n\tbind(client: RivaClient): readonly [V, B];\n}): readonly [V, B] {\n\tconst client = useClient();\n\tconst t = useMemo<Tracker>(\n\t\t() => ({\n\t\t\tkeys: new Set(),\n\t\t\tcommitted: [],\n\t\t\tseen: new Map(),\n\t\t\tver: 0,\n\t\t\ttick: signal(0),\n\t\t}),\n\t\t[client, def],\n\t);\n\n\tconst subscribe = useCallback(\n\t\t(notify: () => void) =>\n\t\t\tclient.effect(() => {\n\t\t\t\tclient.get(t.tick);\n\t\t\t\tlet changed = false;\n\t\t\t\tfor (const m of t.committed) {\n\t\t\t\t\tconst v = client.get(m);\n\t\t\t\t\tif (!Object.is(t.seen.get(m), v)) {\n\t\t\t\t\t\tt.seen.set(m, v);\n\t\t\t\t\t\tchanged = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (changed) {\n\t\t\t\t\tt.ver++;\n\t\t\t\t\tnotify();\n\t\t\t\t}\n\t\t\t}),\n\t\t[client, t],\n\t);\n\tconst read = () => t.ver;\n\tconst ver = useSyncExternalStore(subscribe, read, read);\n\n\tconst a = def.bind(client)[1];\n\t// A new view per version: what read the old one re-renders, and starts a\n\t// new set of keys. Reads made by a render that is not committed stay in `keys`.\n\tconst s = useMemo(() => {\n\t\tt.keys.clear();\n\t\treturn new Proxy(\n\t\t\t{},\n\t\t\t{\n\t\t\t\tget: (_, k) => {\n\t\t\t\t\tconst m = (def as unknown as Record<PropertyKey, unknown>)[k];\n\t\t\t\t\tif (!isMember(m)) return undefined;\n\t\t\t\t\tconst v = client.get(m);\n\t\t\t\t\tt.keys.add(m);\n\t\t\t\t\tt.seen.set(m, v);\n\t\t\t\t\treturn v;\n\t\t\t\t},\n\t\t\t\tset: (_, k) => {\n\t\t\t\t\tthrow new RivaError(\n\t\t\t\t\t\t'RIVA_STORE',\n\t\t\t\t\t\t`Store \"${def.name}\": \"${String(k)}\" is read-only here; write it in an action.`,\n\t\t\t\t\t);\n\t\t\t\t},\n\t\t\t},\n\t\t) as V;\n\t}, [t, ver, a]);\n\n\tuseLayoutEffect(() => {\n\t\tconst next = [...t.keys];\n\t\tif (\n\t\t\tnext.length !== t.committed.length ||\n\t\t\tnext.some((m) => !t.committed.includes(m))\n\t\t) {\n\t\t\tt.committed = next;\n\t\t\tclient.set(t.tick, (n) => n + 1);\n\t\t}\n\t});\n\n\treturn useMemo(() => [s, a] as const, [s, a]);\n}\n"
6
+ ],
7
+ "mappings": ";;;;;AAAA;AAAA;AAAA;AAAA;AAOA;AAAA;AAAA;AAAA;AAAA;AAAA;AAoBA,IAAM,WAAW,CAAC,MAChB,GAAqC,SAAS,YAC9C,GAAqC,SAAS;AAQzC,SAAS,QAAc,CAAC,KAGX;AAAA,EACnB,MAAM,SAAS,WAAU;AAAA,EACzB,MAAM,IAAI,QACT,OAAO;AAAA,IACN,MAAM,IAAI;AAAA,IACV,WAAW,CAAC;AAAA,IACZ,MAAM,IAAI;AAAA,IACV,KAAK;AAAA,IACL,MAAM,OAAO,CAAC;AAAA,EACf,IACA,CAAC,QAAQ,GAAG,CACb;AAAA,EAEA,MAAM,YAAY,YACjB,CAAC,WACA,OAAO,OAAO,MAAM;AAAA,IACnB,OAAO,IAAI,EAAE,IAAI;AAAA,IACjB,IAAI,UAAU;AAAA,IACd,WAAW,KAAK,EAAE,WAAW;AAAA,MAC5B,MAAM,IAAI,OAAO,IAAI,CAAC;AAAA,MACtB,IAAI,CAAC,OAAO,GAAG,EAAE,KAAK,IAAI,CAAC,GAAG,CAAC,GAAG;AAAA,QACjC,EAAE,KAAK,IAAI,GAAG,CAAC;AA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+ "names": []
10
+ }
@@ -0,0 +1,12 @@
1
+ import { type RivaClient } from '@softistx/riva';
2
+ /**
3
+ * A store's state and computeds as `s`, and its actions as `a`, bound to the
4
+ * provider's client. `s` is tracked per key: the component re-renders only
5
+ * when a key it read changes, and `s` is a new object after each change, so
6
+ * `useMemo([s])` and `React.memo` children follow it.
7
+ */
8
+ export declare function useStore<V, B>(def: {
9
+ readonly name: string;
10
+ bind(client: RivaClient): readonly [V, B];
11
+ }): readonly [V, B];
12
+ //# sourceMappingURL=use-store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-store.d.ts","sourceRoot":"","sources":["../../src/store/use-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAEN,KAAK,UAAU,EAIf,MAAM,gBAAgB,CAAC;AAyBxB;;;;;GAKG;AACH,wBAAgB,QAAQ,CAAC,CAAC,EAAE,CAAC,EAAE,GAAG,EAAE;IACnC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,IAAI,CAAC,MAAM,EAAE,UAAU,GAAG,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;CAC1C,GAAG,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,CAyElB"}
@@ -0,0 +1,8 @@
1
+ import type { Query, RivaClient } from '@softistx/riva';
2
+ /**
3
+ * The one promise React waits on for a query entry: the core's `ensure`, held
4
+ * until it settles so every render that suspends gets the same promise. A
5
+ * failure is swallowed here; the next render reads it from the state.
6
+ */
7
+ export declare function suspend(client: RivaClient, def: Query<any, any, any>, key: string, vars: unknown): Promise<void>;
8
+ //# sourceMappingURL=suspend.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"suspend.d.ts","sourceRoot":"","sources":["../src/suspend.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAKxD;;;;GAIG;AACH,wBAAgB,OAAO,CACtB,MAAM,EAAE,UAAU,EAElB,GAAG,EAAE,KAAK,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,EACzB,GAAG,EAAE,MAAM,EACX,IAAI,EAAE,OAAO,GACX,OAAO,CAAC,IAAI,CAAC,CAiBf"}
@@ -0,0 +1,18 @@
1
+ import type { Mutation, QueryStatus, RunOptions, VarsArgs } from '@softistx/riva';
2
+ export interface MutationResult<Vars, Data> {
3
+ /** Runs the mutation: resolves with the server data, rejects with the error (also in `error`). */
4
+ run: (...args: VarsArgs<Vars, [opts?: RunOptions]>) => Promise<Data>;
5
+ status: QueryStatus;
6
+ data: Data | undefined;
7
+ error: unknown;
8
+ isPending: boolean;
9
+ /** Back to `idle`; the result of a run still in flight is dropped from the state. */
10
+ reset: () => void;
11
+ }
12
+ /**
13
+ * Runs a mutation with its own status, data and error, held by this hook
14
+ * instance. A run finishes when its component unmounts; it just stops
15
+ * reporting. When runs overlap, the latest one owns the state.
16
+ */
17
+ export declare function useMutation<Vars, Data>(def: Mutation<Vars, Data>): MutationResult<Vars, Data>;
18
+ //# sourceMappingURL=use-mutation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-mutation.d.ts","sourceRoot":"","sources":["../src/use-mutation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,QAAQ,EACR,WAAW,EACX,UAAU,EACV,QAAQ,EACR,MAAM,gBAAgB,CAAC;AAIxB,MAAM,WAAW,cAAc,CAAC,IAAI,EAAE,IAAI;IACzC,kGAAkG;IAClG,GAAG,EAAE,CAAC,GAAG,IAAI,EAAE,QAAQ,CAAC,IAAI,EAAE,CAAC,IAAI,CAAC,EAAE,UAAU,CAAC,CAAC,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACrE,MAAM,EAAE,WAAW,CAAC;IACpB,IAAI,EAAE,IAAI,GAAG,SAAS,CAAC;IACvB,KAAK,EAAE,OAAO,CAAC;IACf,SAAS,EAAE,OAAO,CAAC;IACnB,qFAAqF;IACrF,KAAK,EAAE,MAAM,IAAI,CAAC;CAClB;AAcD;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,IAAI,EAAE,IAAI,EACrC,GAAG,EAAE,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,GACvB,cAAc,CAAC,IAAI,EAAE,IAAI,CAAC,CAuC5B"}
@@ -0,0 +1,25 @@
1
+ import type { Query, QueryState } from '@softistx/riva';
2
+ export interface UseQueryOptions {
3
+ /** `false` observes nothing and reads `idle`. Default true. */
4
+ enabled?: boolean;
5
+ /** Suspends while there is no data, and throws an error with no data to the nearest error boundary. Default false. */
6
+ suspense?: boolean;
7
+ }
8
+ export type QueryResult<S> = S & {
9
+ /** Marks the entry stale and fetches it; never rejects, read the error from the state. */
10
+ refetch: () => Promise<void>;
11
+ };
12
+ /** The state of a `suspense: true` query: its data is there. */
13
+ export type SuspendedState<S extends QueryState<unknown>> = Omit<S, 'data'> & {
14
+ data: Exclude<S['data'], undefined>;
15
+ };
16
+ type Void = void | undefined;
17
+ type Args<V, O> = [V] extends [Void] ? [vars?: V, opts?: O] : [vars: V, opts?: O];
18
+ type SuspenseArgs<V, O> = [V] extends [Void] ? [vars: V | undefined, opts: O] : [vars: V, opts: O];
19
+ /** A query's state for these variables, fetched while the component is mounted. */
20
+ export declare function useQuery<V, D, S extends QueryState<unknown>>(def: Query<V, D, S>, ...args: SuspenseArgs<V, UseQueryOptions & {
21
+ suspense: true;
22
+ }>): QueryResult<SuspendedState<S>>;
23
+ export declare function useQuery<V, D, S extends QueryState<unknown>>(def: Query<V, D, S>, ...args: Args<V, UseQueryOptions>): QueryResult<S>;
24
+ export {};
25
+ //# sourceMappingURL=use-query.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-query.d.ts","sourceRoot":"","sources":["../src/use-query.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAKxD,MAAM,WAAW,eAAe;IAC/B,+DAA+D;IAC/D,OAAO,CAAC,E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CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAAC;AAClC,wBAAgB,QAAQ,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,SAAS,UAAU,CAAC,OAAO,CAAC,EAC3D,GAAG,EAAE,KAAK,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,EACnB,GAAG,IAAI,EAAE,IAAI,CAAC,CAAC,EAAE,eAAe,CAAC,GAC/B,WAAW,CAAC,CAAC,CAAC,CAAC"}
@@ -0,0 +1,6 @@
1
+ import type { Readable, Signal } from '@softistx/riva';
2
+ /** The value of a signal or computed, re-rendering when it changes. */
3
+ export declare function useValue<T>(def: Readable<T>): T;
4
+ /** A signal's value and its setter (a value or an updater, as the signal's own `set`). */
5
+ export declare function useSignal<T>(def: Signal<T>): [value: T, set: (value: T | ((prev: T) => T)) => void];
6
+ //# sourceMappingURL=use-signal.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-signal.d.ts","sourceRoot":"","sources":["../src/use-signal.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAIvD,uEAAuE;AACvE,wBAAgB,QAAQ,CAAC,CAAC,EAAE,GAAG,EAAE,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,CAQ/C;AAED,0FAA0F;AAC1F,wBAAgB,SAAS,CAAC,CAAC,EAC1B,GAAG,EAAE,MAAM,CAAC,CAAC,CAAC,GACZ,CAAC,KAAK,EAAE,CAAC,EAAE,GAAG,EAAE,CAAC,KAAK,EAAE,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAK,IAAI,CAAC,CAQxD"}
package/docs/README.md ADDED
@@ -0,0 +1,20 @@
1
+ # @softistx/riva-react docs
2
+
3
+ ## Guides
4
+
5
+ - [Provider](./guide/provider.md): read first: `RivaProvider`, `useClient`, one client per tree.
6
+ - [Signals](./guide/signals.md): read for `useSignal` and `useValue` over signals and computeds.
7
+ - [Queries](./guide/queries.md): read for `useQuery`: options, result, `refetch`.
8
+ - [Suspense](./guide/suspense.md): read for `suspense: true`, error boundaries and retry.
9
+ - [Mutations](./guide/mutations.md): read for `useMutation`: status, `run`, `reset`.
10
+ - [Infinite lists](./guide/infinite.md): read for `useInfiniteQuery` and paging.
11
+ - [Entities](./guide/entities.md): read for `useFragment` over the normalized cache.
12
+ - [Stores](./guide/store.md): read for `useStore` and its tracked, read-only state.
13
+ - [Server rendering](./guide/ssr.md): read to render a request on the server.
14
+
15
+ ## Reference
16
+
17
+ - [Troubleshooting](./troubleshooting.md): every error the bindings throw, and the traps (Suspense and error boundaries, stale data), with the fix.
18
+ - [Package README](../README.md): install, the provider, and one example per hook.
19
+ - [Core docs](https://github.com/softistx/riva/blob/develop/packages/riva/docs/README.md): the guides and errors of `@softistx/riva` itself.
20
+ - [Spec](https://github.com/softistx/riva/blob/develop/docs/spec.md): the decision record.
@@ -0,0 +1,25 @@
1
+ # Entities: `@softistx/riva-react/entities`
2
+
3
+ `useFragment` reads one entity of the normalized cache (`@softistx/riva/entities`) by its ref (`Type:id`). The component re-renders when that entity's fields change, and only then.
4
+
5
+ ```tsx
6
+ import { useFragment } from '@softistx/riva-react/entities';
7
+
8
+ function PatientName({ id }: { id: string }) {
9
+ const patient = useFragment<{ name: string }>(`Patient:${id}`);
10
+ return <span>{patient?.name ?? '…'}</span>;
11
+ }
12
+ ```
13
+
14
+ `useFragment<T>(ref)`:
15
+
16
+ | Argument | Meaning |
17
+ | --- | --- |
18
+ | `T` | The entity's type; default `Record<string, unknown>`. |
19
+ | `ref` | `'Type:id'`, or `null` / `undefined`: the hook then reads `undefined`, as it does for a missing entity. |
20
+
21
+ - It reads the committed entity with optimistic layers applied.
22
+ - The queries that fill the cache need `cache: entities()` (or `normalized()` from `@softistx/riva-graphql/cache`); without a cache policy, there is nothing to read.
23
+ - A missing entity reads `undefined`, never throws.
24
+
25
+ Identity rules and the store: the core's [entities guide](https://github.com/softistx/riva/blob/develop/packages/riva/docs/guide/entities.md).
@@ -0,0 +1,35 @@
1
+ # Infinite lists: `@softistx/riva-react/infinite`
2
+
3
+ `useInfiniteQuery` binds a list built with `infinite()` from `@softistx/riva/infinite`. `connection` reads the Relay shape `{ edges: [{ node, cursor }], pageInfo }` out of a page, and `data.nodes` is every loaded page's nodes, flattened.
4
+
5
+ ```tsx
6
+ import { infinite } from '@softistx/riva/infinite';
7
+ import { useInfiniteQuery } from '@softistx/riva-react/infinite';
8
+
9
+ const patientsFeed = infinite({
10
+ id: 'patientsFeed',
11
+ // `after` is the cursor the engine fills in; the caller passes `school` only.
12
+ fetch: ({ school, after }: { school: string; after?: string }) => fetchPatientPage(school, after),
13
+ connection: (page) => page.patients, // { edges: [{ node, cursor }], pageInfo }
14
+ });
15
+
16
+ function Feed({ school }: { school: string }) {
17
+ const { data, hasNext, isFetchingNext, fetchNext } = useInfiniteQuery(patientsFeed, { school });
18
+ return (
19
+ <>
20
+ <ul>{data?.nodes.map((p) => <li key={p.id}>{p.name}</li>)}</ul>
21
+ {hasNext && <button disabled={isFetchingNext} onClick={fetchNext}>More</button>}
22
+ </>
23
+ );
24
+ }
25
+ ```
26
+
27
+ `useInfiniteQuery(def, vars?, opts?)`:
28
+
29
+ | Option | Default | Effect |
30
+ | --- | --- | --- |
31
+ | `enabled` | `true` | `false` observes nothing and reads `idle`. |
32
+
33
+ Returns the list's state (`status`, `data` with `nodes` and `pages`, `error`, `isFetching`, `hasNext`, `hasPrevious`, `isFetchingNext`, `isFetchingPrevious`) plus `fetchNext`, `fetchPrevious` and `refetch` (every loaded page).
34
+
35
+ How a refetch, a page error and `setData` behave: the core's [infinite guide](https://github.com/softistx/riva/blob/develop/packages/riva/docs/guide/infinite.md).
@@ -0,0 +1,41 @@
1
+ # Mutations: `useMutation`
2
+
3
+ `useMutation(def)` holds its status per hook instance. `run` resolves with the server data and rejects with the error (also in `error`); the mutation finishes even if the component unmounts, it only stops reporting. When runs overlap, the latest owns the state.
4
+
5
+ ```tsx
6
+ import { mutation } from '@softistx/riva';
7
+ import { useMutation } from '@softistx/riva-react';
8
+
9
+ const rename = mutation({
10
+ id: 'renamePatient',
11
+ run: (vars: { id: string; name: string }, { signal }) => sendRename(vars, signal), // Promise<Patient>
12
+ invalidates: [patients],
13
+ });
14
+
15
+ function Rename({ id }: { id: string }) {
16
+ const { run, isPending, error, reset } = useMutation(rename);
17
+ return (
18
+ <button disabled={isPending} onClick={() => run({ id, name: 'New name' }).catch(() => {})}>
19
+ Rename
20
+ </button>
21
+ );
22
+ }
23
+ ```
24
+
25
+ ## Result
26
+
27
+ | Field | Meaning |
28
+ | --- | --- |
29
+ | `run(vars, opts?)` | Runs the mutation; `opts` is `{ signal? }`. Resolves with the data, rejects with the error. |
30
+ | `status` | `idle`, `pending`, `success` or `error`. |
31
+ | `data` | The last result of the latest run. |
32
+ | `error` | The last error of the latest run. |
33
+ | `isPending` | `status === 'pending'`. |
34
+ | `reset()` | Back to `idle`, clears `data` and `error`. |
35
+
36
+ The definition's own options (`optimistic`, `updates`, `invalidates`, `cache`, `retry`) apply: see the core's [mutations guide](https://github.com/softistx/riva/blob/develop/packages/riva/docs/guide/mutations.md).
37
+
38
+ ## Traps
39
+
40
+ - `run` rejects: catch it (`.catch(() => {})`) when you read the error from the hook, or you get an unhandled rejection (see [troubleshooting](../troubleshooting.md)).
41
+ - Unmounting does not cancel the mutation; pass a `signal` to `run` to abort it.
@@ -0,0 +1,34 @@
1
+ # The provider and the client
2
+
3
+ One `RivaClient` per tree: one in the browser, one per request on the server. `RivaProvider` puts it in scope for the hooks below it.
4
+
5
+ ```tsx
6
+ import { createRivaClient } from '@softistx/riva';
7
+ import { RivaProvider, useClient } from '@softistx/riva-react';
8
+
9
+ const client = createRivaClient(); // per request on the server
10
+
11
+ export const App = () => (
12
+ <RivaProvider client={client}>
13
+ <Patients />
14
+ </RivaProvider>
15
+ );
16
+
17
+ function RefreshButton() {
18
+ const client = useClient();
19
+ return <button onClick={() => patients.invalidate(client, { school: 'north' })}>Refresh</button>;
20
+ }
21
+ ```
22
+
23
+ | Export | What |
24
+ | --- | --- |
25
+ | `RivaProvider` | Props: `client` (required) and `children`. |
26
+ | `useClient()` | The nearest provider's client. Use it to call `def.invalidate(client, vars)`, `def.ensure(client, vars)` or `def.setData(...)` from an event handler. |
27
+
28
+ Every hook binds through `useSyncExternalStore`, so it is concurrent-safe and renders on the server.
29
+
30
+ ## Traps
31
+
32
+ - A hook with no provider above it throws `RivaScopeError` (`RIVA_SCOPE`: ``No RivaClient in scope: wrap the tree in <RivaProvider client={client}>``).
33
+ - Create the client once per mount in the browser (outside the component or in a `useState` initializer), not on each render. With React Router, `RivaRouterProvider` does it for you.
34
+ - On the server never keep a client at module level: build one per request.
@@ -0,0 +1,41 @@
1
+ # Queries: `useQuery`
2
+
3
+ `useQuery(def, vars?, opts?)` returns the query state (`status`, `data`, `error`, `isFetching`, `updatedAt`) plus `refetch`. It fetches while the component is mounted, when the data is missing or stale. Variables and data are inferred from the definition.
4
+
5
+ ```tsx
6
+ import { query } from '@softistx/riva';
7
+ import { useQuery } from '@softistx/riva-react';
8
+
9
+ const patients = query({
10
+ id: 'patients',
11
+ staleTime: '30s',
12
+ fetch: ({ school }: { school: string }, { signal }) => fetchPatients(school, signal), // Promise<Patient[]>
13
+ });
14
+
15
+ function PatientList({ school }: { school: string }) {
16
+ const { data, status, error, refetch } = useQuery(patients, { school });
17
+ if (status === 'error') return <button onClick={refetch}>Retry: {String(error)}</button>;
18
+ return <ul>{data?.map((p) => <li key={p.id}>{p.name}</li>)}</ul>;
19
+ }
20
+ ```
21
+
22
+ ## Options (`opts`)
23
+
24
+ | Option | Default | Effect |
25
+ | --- | --- | --- |
26
+ | `enabled` | `true` | `false` observes nothing, creates no entry and reads `idle`. Use it for a query that waits on another value. |
27
+ | `suspense` | `false` | The component suspends while there is no data (see [suspense](./suspense.md)). |
28
+
29
+ ## Result
30
+
31
+ `QueryResult<S>` is the definition's state plus `refetch: () => Promise<void>`.
32
+
33
+ - Variables are compared by value (`stableKey`), so an inline `{ school }` never resubscribes.
34
+ - `refetch()` marks the entry stale and fetches it. It never rejects: the error is in the state.
35
+ - A query with no required variables takes none: `useQuery(viewer)`.
36
+ - The definition's own options (`staleTime`, `gcTime`, `retry`, `refetchOnFocus`, `refetchEvery`, ...) decide how often it fetches: see the core's [queries guide](https://github.com/softistx/riva/blob/develop/packages/riva/docs/guide/queries.md).
37
+
38
+ ## Traps
39
+
40
+ - A hook never starts a fetch during a server render, except with `suspense: true`. Load data in a loader (`@softistx/riva-react-router`) or `ensure` it before rendering.
41
+ - `useQuery` observes: unmounting the last observer lets the entry be collected after `gcTime`.
@@ -0,0 +1,27 @@
1
+ # Signals and computeds: `useSignal`, `useValue`
2
+
3
+ ```tsx
4
+ import { computed, signal } from '@softistx/riva';
5
+ import { useSignal, useValue } from '@softistx/riva-react';
6
+
7
+ const filter = signal('');
8
+ const hasFilter = computed((get) => get(filter).length > 0);
9
+
10
+ function Search() {
11
+ const [q, setQ] = useSignal(filter); // setQ takes a value or an updater
12
+ const active = useValue(hasFilter); // a signal or a computed
13
+ return <input value={q} data-active={active} onChange={(e) => setQ(e.target.value)} />;
14
+ }
15
+ ```
16
+
17
+ | Hook | Takes | Returns |
18
+ | --- | --- | --- |
19
+ | `useSignal(signal)` | a `Signal<T>` | `[value, set]`; `set` takes a value or `(prev) => next` |
20
+ | `useValue(readable)` | a signal or a computed | the current value, read-only |
21
+
22
+ - The component re-renders when the value changes by the definition's `equals` (default `Object.is`).
23
+ - Values are held by the provider's client, so two requests, or two clients in a test, never share one.
24
+ - Under `renderToString` the hooks read the provider's client.
25
+ - `useValue(Store.key)` reads one value of a store; see [store](./store.md) for `useStore`.
26
+
27
+ Definitions, options (`name`, `equals`, `ssr`) and effects: the core's [signals guide](https://github.com/softistx/riva/blob/develop/packages/riva/docs/guide/signals.md).
@@ -0,0 +1,27 @@
1
+ # Server rendering
2
+
3
+ Render each request under its own `RivaProvider` with its own client; no hook holds module-level state, so nothing leaks between requests.
4
+
5
+ ```tsx
6
+ import { createRivaClient } from '@softistx/riva';
7
+ import { RivaProvider } from '@softistx/riva-react';
8
+ import { renderToReadableStream } from 'react-dom/server';
9
+
10
+ export async function handle(school: string): Promise<Response> {
11
+ const client = createRivaClient(); // one per request
12
+ await patients.ensure(client, { school }); // so the first render has data
13
+ const stream = await renderToReadableStream(
14
+ <RivaProvider client={client}>
15
+ <PatientList school={school} />
16
+ </RivaProvider>,
17
+ );
18
+ return new Response(stream, { headers: { 'content-type': 'text/html' } });
19
+ }
20
+ ```
21
+
22
+ - A hook never starts a fetch during a server render, except through `suspense: true`, which waits for it and streams the result (`renderToReadableStream` and `renderToPipeableStream`).
23
+ - Effects and subscriptions run in the browser only.
24
+ - To hand the server's cache to the browser, use `dehydrate` and `hydrate` from `@softistx/riva/ssr`, or `@softistx/riva-react-router`, which does both. Until the browser has the snapshot, it fetches what it does not have.
25
+ - Data hydrated with a `staleTime` of 0 is refetched at once: give queries a `staleTime`.
26
+
27
+ See the core's [ssr guide](https://github.com/softistx/riva/blob/develop/packages/riva/docs/guide/ssr.md).
@@ -0,0 +1,27 @@
1
+ # Stores: `@softistx/riva-react/store`
2
+
3
+ `useStore(def)` binds a store built with `store()` from `@softistx/riva/store`. It returns `[s, a]`: `s` is the state and the computeds, `a` the actions bound to the provider's client (stable for that client).
4
+
5
+ ```tsx
6
+ import { useStore } from '@softistx/riva-react/store';
7
+
8
+ function Books() {
9
+ const [s, a] = useStore(BookStore);
10
+ return (
11
+ <>
12
+ <input value={s.filter} onChange={(e) => a.filterBy(e.target.value)} />
13
+ <p>{s.total} books</p>
14
+ <ul>{s.visible.map((b) => <li key={b.title}>{b.title}</li>)}</ul>
15
+ <button onClick={() => a.add({ title: 'New' })}>Add</button>
16
+ </>
17
+ );
18
+ }
19
+ ```
20
+
21
+ - `s` is tracked per key: the component re-renders only when a key it read during its render changes. `s.total` alone does not re-render on a `filter` change.
22
+ - `s` is read-only: a write throws a `RivaError` with code `RIVA_STORE` (``Store "books": "filter" is read-only here; write it in an action.``). Write through `a`.
23
+ - `s` is a new object after each change of a key the component read, so `useMemo(…, [s])` and `React.memo` children that take `s` follow it.
24
+ - `useValue(BookStore.total)` still reads a single value.
25
+ - Under `renderToString` the hook reads the provider's client.
26
+
27
+ Defining a store, the action context and names: the core's [store guide](https://github.com/softistx/riva/blob/develop/packages/riva/docs/guide/store.md).
@@ -0,0 +1,38 @@
1
+ # Suspense
2
+
3
+ With `suspense: true`, `useQuery` suspends while there is no data, and `data` is no longer optional in its type. A failure with no data is thrown to the nearest error boundary. With `enabled: false` it never suspends: the query reads `idle`.
4
+
5
+ ```tsx
6
+ import { Suspense } from 'react';
7
+ import { ErrorBoundary } from 'react-error-boundary';
8
+ import { useClient, useQuery } from '@softistx/riva-react';
9
+
10
+ function PatientList({ school }: { school: string }) {
11
+ const { data } = useQuery(patients, { school }, { suspense: true });
12
+ return <ul>{data.map((p) => <li key={p.id}>{p.name}</li>)}</ul>; // data: Patient[]
13
+ }
14
+
15
+ export function Page({ school }: { school: string }) {
16
+ const client = useClient();
17
+ return (
18
+ <ErrorBoundary fallback={<p>Failed</p>} onReset={() => patients.prefetch(client, { school })}>
19
+ <Suspense fallback={<p>Loading…</p>}>
20
+ <PatientList school={school} />
21
+ </Suspense>
22
+ </ErrorBoundary>
23
+ );
24
+ }
25
+ ```
26
+
27
+ `ErrorBoundary` is the one of [react-error-boundary](https://www.npmjs.com/package/react-error-boundary); any error boundary works.
28
+
29
+ ## Behaviour
30
+
31
+ - What a Suspense render fetched is not fetched again when the component mounts, whatever the query's `staleTime` (the hook subscribes with `{ staleTime: 1000 }`).
32
+ - After an entity is evicted, a suspending component suspends again while the query refetches.
33
+ - On the server, `suspense: true` waits for the fetch and streams the result (`renderToReadableStream` and `renderToPipeableStream`).
34
+
35
+ ## Traps
36
+
37
+ - To retry after an error, start the fetch again **before** resetting the boundary (`onReset={() => def.prefetch(client, vars)}`), or the boundary re-renders the cached error: see [troubleshooting](../troubleshooting.md).
38
+ - A suspending query with no `staleTime` can fetch twice around the Suspense boundary: see [troubleshooting](../troubleshooting.md).