Skip to content

Commit

Permalink
small tweaks to functions
Browse files Browse the repository at this point in the history
  • Loading branch information
brainkim committed Aug 31, 2019
1 parent 258a5de commit 08babd7
Showing 1 changed file with 6 additions and 8 deletions.
14 changes: 6 additions & 8 deletions src/react-hooks.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import { useEffect, useState } from "react";
import { Push, Repeater, RepeaterBuffer, Stop } from "@repeaterjs/repeater";

type PrimedRepeaterTuple<T> = [Repeater<T>, Push<T>, Stop];
// Repeaters are lazy, hooks are eager.
// We need to return push and stop synchronously from the useRepeater hook so
// we prime the repeater by calling next immediately.
function createPrimedRepeater<T>(
buffer?: RepeaterBuffer<T>,
): PrimedRepeaterTuple<T> {
): [Repeater<T>, Push<T>, Stop] {
let push: Push<T>;
let stop: Stop;
const repeater = new Repeater((push1, stop1) => {
Expand All @@ -23,30 +22,29 @@ function createPrimedRepeater<T>(

export function useRepeater<T>(
buffer?: RepeaterBuffer<T>,
): PrimedRepeaterTuple<T> {
const [tuple] = useState(() => createPrimedRepeater(buffer));
return tuple;
): [Repeater<T>, Push<T>, Stop] {
const [tuple] = useState(() => createPrimedRepeater(buffer));
return tuple;
}

export function useAsyncIter<T, TDeps extends any[]>(
callback: (deps: AsyncIterableIterator<TDeps>) => AsyncIterableIterator<T>,
deps: TDeps = ([] as unknown) as TDeps,
): AsyncIterableIterator<T> {
const [repeater, push, stop] = useRepeater<TDeps>();
const [repeater, push] = useRepeater<TDeps>();
const [iter] = useState(() => callback(repeater));
useEffect(() => {
push(deps);
}, [push, ...deps]); // eslint-disable-line react-hooks/exhaustive-deps

useEffect(
() => () => {
stop();
if (iter.return != null) {
// TODO: handle return errors
iter.return().catch();
}
},
[iter, stop],
[iter],
);

return iter;
Expand Down

0 comments on commit 08babd7

Please sign in to comment.