Skip to content

Commit

Permalink
feat: make dependency list optional (#131)
Browse files Browse the repository at this point in the history
The dependency list is optional in the React useEffect hook
  • Loading branch information
juho-ylikyla committed Oct 21, 2021
1 parent 819f9ca commit 21d20ad
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 2 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@ function useAsyncEffect(
) => void,
cast: <T>(promise: Promise<T>) => Generator<Promise<T>, T>
) => Iterator<any, any, any>,
deps: React.DependencyList
deps?: React.DependencyList
): void;
```

Expand Down
27 changes: 27 additions & 0 deletions src/use-async-effect.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,33 @@ it("calls the generator again once a dependency changes", () => {
expect(callable).toHaveBeenCalledTimes(2);
});


it("calls the generator on each render if no dependency list given", () => {
const callable = jest.fn();

let setState = (() => undefined) as (str: string) => void;

const TestComponent: React.FC = () => {
const [, _setState] = React.useState<string>("hello");
useAsyncEffect(function* () {
callable();
});
setState = _setState;
return null;
};

render(<TestComponent />);

act(() => {
setState("aye");
});
act(() => {
setState("bye");
});

expect(callable).toHaveBeenCalledTimes(3);
});

it("yield can resolve a non promise object", () => {
const callable = jest.fn();

Expand Down
2 changes: 1 addition & 1 deletion src/use-async-effect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export const useAsyncEffect = (
) => void,
cast: <T>(promise: Promise<T>) => Generator<Promise<T>, T>
) => Iterator<unknown, GeneratorReturnValueType>,
deps: React.DependencyList
deps?: React.DependencyList
): void => {
const generatorRef = useRef(createGenerator);

Expand Down

0 comments on commit 21d20ad

Please sign in to comment.