Skip to content
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

useAsyncEffect hook #35

Merged
merged 8 commits into from
Sep 3, 2020
Merged
Show file tree
Hide file tree
Changes from 7 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
89 changes: 89 additions & 0 deletions src/hooks/use-async-effect.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import React from "react";
import "jest-extended";
myty marked this conversation as resolved.
Show resolved Hide resolved
import { cleanup, render, waitFor } from "@testing-library/react";
import { useAsyncEffect, AsyncEffectCallback } from "./use-async-effect";

const sleep = async (milliseconds: number): Promise<void> => {
myty marked this conversation as resolved.
Show resolved Hide resolved
await new Promise((resolve) => {
setTimeout(() => resolve(), milliseconds);
});
};

describe("useAsyncEffect", () => {
const setupUseAsyncEffect = (asyncEffect: AsyncEffectCallback) => {
const TestComponent = () => {
useAsyncEffect(asyncEffect, []);
return null;
};

render(<TestComponent />);
};

test("executes async method", async () => {
// Arrange
const mockedMethod = jest.fn();

// Act
setupUseAsyncEffect(async () => {
await sleep(1);
mockedMethod();
});

// Assert
await waitFor(() => expect(mockedMethod).toBeCalledTimes(1));
await cleanup();
});

test("executes cleanup method", async () => {
// Arrange
const mockedMethod = jest.fn();
const mockedCleanupMethod = jest.fn();

// Act
setupUseAsyncEffect(async () => {
await sleep(1);
mockedMethod();
return mockedCleanupMethod;
});

// Assert
await waitFor(() => expect(mockedMethod).toBeCalledTimes(1));
await cleanup();
await waitFor(() => expect(mockedCleanupMethod).toBeCalledTimes(1));
});

test("isMounted initially equals true", async () => {
// Arrange
let actualIsMountedValue: boolean = false;
const expectedIsMountedValue: boolean = true;

// Act
setupUseAsyncEffect(async (isMounted) => {
actualIsMountedValue = isMounted();
await sleep(1);
});

// Assert
expect(actualIsMountedValue).toBe(expectedIsMountedValue);
await cleanup();
});

test("isMounted equals false after cleanup", async () => {
// Arrange
let actualIsMountedValue: boolean;
const expectedIsMountedValue: boolean = false;
const mockedMethod = jest.fn();

// Act
setupUseAsyncEffect(async (isMounted) => {
await sleep(100);
actualIsMountedValue = isMounted();
mockedMethod();
});

// Assert
await cleanup();
await waitFor(() => expect(mockedMethod).toBeCalledTimes(1));
expect(actualIsMountedValue).toBe(expectedIsMountedValue);
});
});
37 changes: 37 additions & 0 deletions src/hooks/use-async-effect.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { useEffect, DependencyList, EffectCallback, useCallback } from "react";
import { AsyncEffectCallback } from "../types/async-effect-callback-type";

/**
* Version of the useEffect hook that accepts an async function
* @export
* @param {AsyncEffectCallback} asyncEffect
* @param {DependencyList} deps
*/
export function useAsyncEffect(
asyncEffect: AsyncEffectCallback,
deps: DependencyList
) {
const asyncCallback = useCallback<AsyncEffectCallback>(asyncEffect, deps);

useEffect(() => {
let cleanupMethod = () => {};
let isMounted = true;

async function runAsyncCallback() {
const result: ReturnType<EffectCallback> = await asyncCallback(
() => isMounted
);

if (typeof result === "function") {
cleanupMethod = result;
}
}

runAsyncCallback();

return () => {
cleanupMethod();
isMounted = false;
};
}, [asyncCallback]);
}
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export { Redirects, RedirectsProps } from "./components/routing/redirects";
// -----------------------------------------------------------------------------------------

export { makeCancellable } from "./hooks/make-cancellable";
export { useAsyncEffect } from "./hooks/use-async-effect";
export { useCancellablePromise } from "./hooks/use-cancellable-promise";
export { useDebounce } from "./hooks/use-debounce";
export { useLocalization } from "./hooks/use-localization";
Expand Down Expand Up @@ -61,6 +62,7 @@ export { ServiceHookFactory } from "./services/service-hook-factory";
// #region Types
// -----------------------------------------------------------------------------------------

export { AsyncEffectCallback } from "./types/async-effect-callback-type";
export { BulkUpdateService } from "./types/bulk-update-service-type";
export { BulkUpdateServiceHook } from "./types/bulk-update-service-hook-type";
export { CreateService } from "./types/create-service-type";
Expand Down
8 changes: 8 additions & 0 deletions src/types/async-effect-callback-type.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { EffectCallback } from "react";

/**
* Type defining the asyncEffect parameter from calling `useAsyncEffect()`
*/
export type AsyncEffectCallback = (
isMounted: () => boolean
) => Promise<ReturnType<EffectCallback>>;