1
1
import { useEffect , useRef } from 'react' ;
2
2
import { IterableChannel } from './IterableChannel.js' ;
3
+ import { type Iterate } from '../Iterate/index.js' ; // eslint-disable-line @typescript-eslint/no-unused-vars
3
4
4
5
export { useAsyncIterState , type AsyncIterStateResult } ;
5
6
6
7
/**
7
- * ... ... ...
8
+ * Basically like {@link https://react.dev/reference/react/useState `React.useState`}, only that the value
9
+ * is provided back __wrapped as an async iterable__.
10
+ *
11
+ * This hook allows a component to declare and manage a piece of state while easily letting it control
12
+ * what area(s) specifically within the UI would be bound to it (will re-render in reaction to changes in it) -
13
+ * combined for example with one or more {@link Iterate `<Iterate>`}s.
14
+ *
15
+ * ```tsx
16
+ * import { useAsyncIterState, Iterate } from 'async-react-iterators';
17
+ *
18
+ * function MyForm() {
19
+ * const [firstNameIter, setFirstName] = useAsyncIterState<string>();
20
+ * const [lastNameIter, setLastName] = useAsyncIterState<string>();
21
+ * return (
22
+ * <div>
23
+ * <form>
24
+ * <FirstNameInput valueIter={firstNameIter} onChange={setFirstName} />
25
+ * <LastNameInput valueIter={lastNameIter} onChange={setLastName} />
26
+ * </form>
27
+ *
28
+ * Greetings, <Iterate>{firstNameIter}</Iterate> <Iterate>{lastNameIter}</Iterate>
29
+ * </div>
30
+ * )
31
+ * }
32
+ * ```
33
+ *
34
+ * This is unlike vanila `React.useState` which simply re-renders the entire component. Instead,
35
+ * `useAsyncIterState` helps confine UI updates as well as facilitate layers of sub-components that pass
36
+ * actual async iterables across one another as props, skipping typical cascading re-renderings down to
37
+ * __only the inner-most leafs__ of the UI tree.
38
+ *
39
+ * The returned async iterable is sharable; it can be iterated by multiple consumers concurrently
40
+ * (e.g multiple {@link Iterate `<Iterate>`}s) all see the same yields at the same time.
41
+ *
42
+ * The returned async iterable is automatically closed on host component unmount.
43
+ *
44
+ * @template TVal the type of state to be set and yielded by returned iterable.
45
+ *
46
+ * @returns a stateful async iterable and a function with which to yield an update, both maintain stable
47
+ * references across re-renders.
48
+ *
49
+ * @see {@link Iterate `<Iterate>` }
8
50
*/
9
51
function useAsyncIterState < TVal > ( ) : AsyncIterStateResult < TVal > {
10
52
const ref = useRef < {
@@ -29,4 +71,10 @@ function useAsyncIterState<TVal>(): AsyncIterStateResult<TVal> {
29
71
return result ;
30
72
}
31
73
74
+ /**
75
+ * The pair of stateful async iterable and a function with which to yield an update.
76
+ * Returned from the {@link useAsyncIterState `useAsyncIterState`} hook.
77
+ *
78
+ * @see {@link useAsyncIterState `useAsyncIterState` }
79
+ */
32
80
type AsyncIterStateResult < TVal > = [ AsyncIterable < TVal , void , void > , ( newValue : TVal ) => void ] ;
0 commit comments