Skip to content

Add useAsyncIterState hook #16

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Dec 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
"@eslint/js": "^9.17.0",
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.1.0",
"@types/lodash-es": "^4.17.12",
"@types/node": "^22.10.2",
"@types/react": "^18.2.47",
"@types/react-dom": "^18.0.11",
Expand All @@ -66,6 +67,7 @@
"eslint-config-prettier": "^9.1.0",
"globals": "^15.13.0",
"jsdom": "^25.0.1",
"lodash-es": "^4.17.21",
"prettier": "^3.4.2",
"typescript": "^5.7.2",
"typescript-eslint": "^8.18.0",
Expand Down
23 changes: 23 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

100 changes: 100 additions & 0 deletions spec/tests/useAsyncIterState.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import { it, describe, expect, afterEach } from 'vitest';
import { gray } from 'colorette';
import { range } from 'lodash-es';
import { renderHook, cleanup as cleanupMountedReactTrees, act } from '@testing-library/react';
import { useAsyncIterState } from '../../src/index.js';
import { asyncIterToArray } from '../utils/asyncIterToArray.js';
import { asyncIterTake } from '../utils/asyncIterTake.js';
import { pipe } from '../utils/pipe.js';

afterEach(() => {
cleanupMountedReactTrees();
});

describe('`useAsyncIterState` hook', () => {
it(gray('The returned iterable can be async-iterated upon successfully'), async () => {
const [values, setValue] = renderHook(() => useAsyncIterState<string>()).result.current;

const valuesToSet = ['a', 'b', 'c'];

const collectPromise = pipe(values, asyncIterTake(valuesToSet.length), asyncIterToArray);

for (const value of valuesToSet) {
await act(() => setValue(value));
}

expect(await collectPromise).toStrictEqual(['a', 'b', 'c']);
});

it(
gray(
'When hook is unmounted, all outstanding yieldings of the returned iterable resolve to "done"'
),
async () => {
const renderedHook = renderHook(() => useAsyncIterState<string>());
const [values] = renderedHook.result.current;

const [collectPromise1, collectPromise2] = range(2).map(() => asyncIterToArray(values));

renderedHook.unmount();

const collections = await Promise.all([collectPromise1, collectPromise2]);
expect(collections).toStrictEqual([[], []]);
}
);

it(
gray(
'After setting some values followed by unmounting the hook, the pre-unmounting values go through while further values pulled from the returned iterable are always "done"'
),
async () => {
const renderedHook = renderHook(() => useAsyncIterState<string>());
const [values, setValue] = renderedHook.result.current;

const [collectPromise1, collectPromise2] = range(2).map(() => asyncIterToArray(values));

await act(() => setValue('a'));

renderedHook.unmount();

const collections = await Promise.all([collectPromise1, collectPromise2]);
expect(collections).toStrictEqual([['a'], ['a']]);
}
);

it(
gray(
'After the hook is unmounted, any further values pulled from the returned iterable are always "done"'
),
async () => {
const renderedHook = renderHook(() => useAsyncIterState<string>());
const [values] = renderedHook.result.current;

renderedHook.unmount();

const collections = await Promise.all(range(2).map(() => asyncIterToArray(values)));
expect(collections).toStrictEqual([[], []]);
}
);

it(
gray(
"The returned iterable's values are each shared between all its parallel consumers so that each receives all the values from the start of consumption and onwards"
),
async () => {
const [values, setValue] = renderHook(() => useAsyncIterState<string>()).result.current;

const consumeStacks: string[][] = [];

for (const [i, value] of ['a', 'b', 'c'].entries()) {
consumeStacks[i] = [];
(async () => {
for await (const v of values) consumeStacks[i].push(v);
})();
await act(() => setValue(value));
}

expect(consumeStacks).toStrictEqual([['a', 'b', 'c'], ['b', 'c'], ['c']]);
}
);
});
45 changes: 45 additions & 0 deletions spec/utils/asyncIterTake.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
export { asyncIterTake };

function asyncIterTake<T>(count: number): (src: AsyncIterable<T>) => AsyncIterable<T> {
return sourceIter => {
let iterator: AsyncIterator<T>;
let remainingCount = count;
let closed = false;

return {
[Symbol.asyncIterator]: () => ({
async next() {
if (closed) {
return { done: true, value: undefined };
}

iterator ??= sourceIter[Symbol.asyncIterator]();

if (remainingCount === 0) {
closed = true;
await iterator.return?.();
return { done: true, value: undefined };
}

remainingCount--;
const next = await iterator.next();

if (next.done) {
closed = true;
return { done: true, value: undefined };
}

return next;
},

async return() {
if (!closed) {
closed = true;
await iterator?.return?.();
}
return { done: true, value: undefined };
},
}),
};
};
}
6 changes: 3 additions & 3 deletions spec/utils/asyncIterToArray.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
export { asyncIterToArray };

async function asyncIterToArray<T>(source: AsyncIterable<T>): Promise<T[]> {
const values: T[] = [];
const collected: T[] = [];
for await (const value of source) {
values.push(value);
collected.push(value);
}
return values;
return collected;
}
4 changes: 2 additions & 2 deletions src/Iterate/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,8 @@ export { Iterate, type IterateProps };
*
* @param props Props for `<Iterate>`. See {@link IterateProps `IterateProps`}.
*
* @returns A renderable output that's re-rendered as consequent values become available and
* formatted by the function passed as `children` (or otherwise the resolved values as-are).
* @returns A React node that updates its contents in response to each next yielded value automatically as
* formatted by the function passed as `children` (or in the absent of, just the yielded values as-are).
*
* @see {@link IterationResult}
*
Expand Down
24 changes: 24 additions & 0 deletions src/common/promiseWithResolvers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
export { promiseWithResolvers, type PromiseWithResolvers };

const promiseWithResolvers: <T>() => PromiseWithResolvers<T> =
'withResolvers' in Promise
? () => Promise.withResolvers()
: /**
* A ponyfill for the [`Promise.withResolvers`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/withResolvers) helper
* @returns A pending {@link PromiseWithResolvers} instance for use
*/
function promiseWithResolversPonyfill<T>(): PromiseWithResolvers<T> {
let resolve!: PromiseWithResolvers<T>['resolve'];
let reject!: PromiseWithResolvers<T>['reject'];
const promise = new Promise<T>((res, rej) => {
resolve = res;
reject = rej;
});
return { promise, resolve, reject };
};

type PromiseWithResolvers<T> = {
promise: Promise<T>;
resolve(value: T): void;
reject(reason?: unknown): void;
};
3 changes: 3 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { useAsyncIter, type IterationResult } from './useAsyncIter/index.js';
import { Iterate, type IterateProps } from './Iterate/index.js';
import { iterateFormatted, type FixedRefFormattedIterable } from './iterateFormatted//index.js';
import { useAsyncIterState, type AsyncIterStateResult } from './useAsyncIterState/index.js';

export {
useAsyncIter,
Expand All @@ -9,4 +10,6 @@ export {
type IterateProps,
iterateFormatted,
type FixedRefFormattedIterable,
useAsyncIterState,
type AsyncIterStateResult,
};
25 changes: 25 additions & 0 deletions src/useAsyncIterState/IterableChannel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { promiseWithResolvers } from '../common/promiseWithResolvers.js';

export { IterableChannel };

class IterableChannel<TVal> {
#isClosed = false;
#nextIteration = promiseWithResolvers<IteratorResult<TVal, void>>();
iterable = {
[Symbol.asyncIterator]: () => ({
next: () => this.#nextIteration.promise,
}),
};

put(value: TVal): void {
if (!this.#isClosed) {
this.#nextIteration.resolve({ done: false, value });
this.#nextIteration = promiseWithResolvers();
}
}

close(): void {
this.#isClosed = true;
this.#nextIteration.resolve({ done: true, value: undefined });
}
}
80 changes: 80 additions & 0 deletions src/useAsyncIterState/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { useEffect, useRef } from 'react';
import { IterableChannel } from './IterableChannel.js';
import { type Iterate } from '../Iterate/index.js'; // eslint-disable-line @typescript-eslint/no-unused-vars

export { useAsyncIterState, type AsyncIterStateResult };

/**
* Basically like {@link https://react.dev/reference/react/useState `React.useState`}, only that the value
* is provided back __wrapped as an async iterable__.
*
* This hook allows a component to declare and manage a piece of state while easily letting it control
* what area(s) specifically within the UI would be bound to it (will re-render in reaction to changes in it) -
* combined for example with one or more {@link Iterate `<Iterate>`}s.
*
* ```tsx
* import { useAsyncIterState, Iterate } from 'async-react-iterators';
*
* function MyForm() {
* const [firstNameIter, setFirstName] = useAsyncIterState<string>();
* const [lastNameIter, setLastName] = useAsyncIterState<string>();
* return (
* <div>
* <form>
* <FirstNameInput valueIter={firstNameIter} onChange={setFirstName} />
* <LastNameInput valueIter={lastNameIter} onChange={setLastName} />
* </form>
*
* Greetings, <Iterate>{firstNameIter}</Iterate> <Iterate>{lastNameIter}</Iterate>
* </div>
* )
* }
* ```
*
* This is unlike vanila `React.useState` which simply re-renders the entire component. Instead,
* `useAsyncIterState` helps confine UI updates as well as facilitate layers of sub-components that pass
* actual async iterables across one another as props, skipping typical cascading re-renderings down to
* __only the inner-most leafs__ of the UI tree.
*
* The returned async iterable is sharable; it can be iterated by multiple consumers concurrently
* (e.g multiple {@link Iterate `<Iterate>`}s) all see the same yields at the same time.
*
* The returned async iterable is automatically closed on host component unmount.
*
* @template TVal the type of state to be set and yielded by returned iterable.
*
* @returns a stateful async iterable and a function with which to yield an update, both maintain stable
* references across re-renders.
*
* @see {@link Iterate `<Iterate>`}
*/
function useAsyncIterState<TVal>(): AsyncIterStateResult<TVal> {
const ref = useRef<{
channel: IterableChannel<TVal>;
result: AsyncIterStateResult<TVal>;
}>();

if (!ref.current) {
const channel = new IterableChannel<TVal>();
ref.current = {
channel,
result: [channel.iterable, newVal => channel.put(newVal)],
};
}

const { channel, result } = ref.current;

useEffect(() => {
return () => channel.close();
}, []);

return result;
}

/**
* The pair of stateful async iterable and a function with which to yield an update.
* Returned from the {@link useAsyncIterState `useAsyncIterState`} hook.
*
* @see {@link useAsyncIterState `useAsyncIterState`}
*/
type AsyncIterStateResult<TVal> = [AsyncIterable<TVal, void, void>, (newValue: TVal) => void];
Loading