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

Migrate usePromise from react-use #1048

Closed
wants to merge 6 commits into from
Closed
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 README.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,8 @@ Coming from `react-use`? Check out our
— Like `useLayoutEffect` but falls back to `useEffect` during SSR.
- [**`useMountEffect`**](https://react-hookz.github.io/web/?path=/docs/lifecycle-usemounteffect--example)
— Run an effect only when a component mounts.
- [**`usePromise`**](https://react-hookz.github.io/web/?path=/docs/lifecycle-usepromise--example)
— Resolves promise only while component is mounted.
- [**`useRafEffect`**](https://react-hookz.github.io/web/?path=/docs/lifecycle-useRafEffect--example)
— Like `useEffect`, but the effect is only run within an animation frame.
- [**`useRerender`**](https://react-hookz.github.io/web/?path=/docs/lifecycle-usererender--example)
Expand Down
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,3 +116,5 @@ export { resolveHookState } from './util/resolveHookState';
export * from './types';

export { useDeepCompareMemo } from './useDeepCompareMemo/useDeepCompareMemo';

export { usePromise } from './usePromise/usePromise';
31 changes: 31 additions & 0 deletions src/usePromise/__docs__/example.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import * as React from 'react';
import { useState, useEffect } from 'react';
import { usePromise } from '../..';

export const Example: React.FC = () => {
const mounted = usePromise();
const [value, setValue] = useState<string>();

const myPromise = new Promise((resolve) => {
setTimeout(() => {
resolve('foo');
}, 300);
});

useEffect(() => {
(async () => {
const res = await mounted(myPromise);

if (typeof res === 'string') {
// This line will not execute if this component gets unmounted.
setValue(res);
}
})();
});

return (
<div>
<button>{value}</button>
</div>
);
};
32 changes: 32 additions & 0 deletions src/usePromise/__docs__/story.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { Canvas, Meta, Story } from '@storybook/addon-docs/blocks';
import { Example } from './example.stories';
import { ImportPath } from '../../storybookUtil/ImportPath';

<Meta title="New Hook/usePromise" component={Example} />

# usePromise

React lifecycle hook that returns a helper function for wrapping promises. Promises wrapped with this function will resolve only if component is mounted.

#### Example

<Canvas>
<Story story={Example} inline />
</Canvas>

## Reference

```ts
usePromise =
() =>
<T>(promise: Promise<T>) =>
Promise<T>;
```

#### Importing

<ImportPath />

#### Return

_`(promise: Promise<T>) => Promise<T>`_ — Function wrapper that for a promise.
29 changes: 29 additions & 0 deletions src/usePromise/__tests__/dom.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { renderHook } from '@testing-library/react-hooks/dom';
import { usePromise } from '../..';

describe('usePromise', () => {
const thenFn = jest.fn();
const resolves = Promise.resolve(thenFn);
const rejects = Promise.reject(Error);

it('should be defined', () => {
expect(usePromise).toBeDefined();
});

it('should render', () => {
const { result } = renderHook(() => usePromise());
expect(result.error).toBeUndefined();
});

it('should return resolved value', async () => {
const { result } = renderHook(() => usePromise());

await expect(result.current(resolves)).resolves.toBe(thenFn);
});

it('should return rejection value', async () => {
const { result } = renderHook(() => usePromise());

await expect(result.current(rejects)).rejects.toBe(Error);
});
});
13 changes: 13 additions & 0 deletions src/usePromise/__tests__/ssr.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { renderHook } from '@testing-library/react-hooks/server';
import { usePromise } from '../..';

describe('usePromise', () => {
it('should be defined', () => {
expect(usePromise).toBeDefined();
});

it('should render', () => {
const { result } = renderHook(() => usePromise());
expect(result.error).toBeUndefined();
});
});
21 changes: 21 additions & 0 deletions src/usePromise/usePromise.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { useCallback } from 'react';
import { useIsMounted } from '../useIsMounted/useIsMounted';

export type UsePromise = () => <T>(promise: Promise<T>) => Promise<T>;

export const usePromise: UsePromise = () => {
const isMounted = useIsMounted();

return useCallback(
<T>(promise: Promise<T>) =>
new Promise<T>((resolve, reject) => {
const onResolve = (resolution: T) => isMounted() && resolve(resolution);

const onReject = (rejection: unknown) => isMounted() && reject(rejection);

// eslint-disable-next-line promise/catch-or-return
promise.then(onResolve, onReject);
}),
[isMounted]
);
};