-
Notifications
You must be signed in to change notification settings - Fork 100
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(useAsyncActionHandler): add useAsyncActionHandler hook
- Loading branch information
kseniyakuzina
committed
Nov 8, 2023
1 parent
f31d5a5
commit 6313ddb
Showing
9 changed files
with
233 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,89 @@ | ||
<!--GITHUB_BLOCK--> | ||
|
||
# useAsyncActionHandler | ||
|
||
<!--/GITHUB_BLOCK--> | ||
|
||
```tsx | ||
import {useAsyncActionHandler} from '@gravity-ui/uikit'; | ||
``` | ||
|
||
The `useAsyncActionHandler` hook wraps an asynchronous action handler to add a loading state to it. | ||
Starts the loading process before executing the passed action and terminates the process after executing the action. | ||
Returns the loading state and the wrapped action handler | ||
|
||
## Properties | ||
|
||
| Name | Description | Type | Default | | ||
| :------ | :------------- | :-----------------------------------------: | :-----: | | ||
| handler | action handler | `(...args: unknown[]) => Promise<unknown>;` | | | ||
|
||
## Result | ||
|
||
```ts | ||
{ | ||
isLoading: boolean; | ||
handler: typeof handler; | ||
} | ||
``` | ||
|
||
Usage: | ||
|
||
```tsx | ||
const action = useCallback(() => Promise.resolve(), []); | ||
|
||
const {isLoading, handler: handleAction} = useAsyncActionHandler({handler: action}); | ||
``` | ||
|
||
### Examples | ||
|
||
Button with automatic loading during click handler execution | ||
|
||
```tsx | ||
type ProgressButtonProps = { | ||
onClick: (event: React.MouseEvent<HTMLButtonElement>) => Promise<unknown>; | ||
} & Exclude<ButtonProps, 'onClick'>; | ||
|
||
export const ProgressButton = (props: ProgressButtonProps) => { | ||
const {onClick, loading: providedIsLoading} = props; | ||
|
||
const {isLoading, handler: handleClick} = useAsyncActionHandler({handler: onClick}); | ||
|
||
return <Button {...props} onClick={handleClick} loading={isLoading || providedIsLoading} />; | ||
}; | ||
|
||
export const LoadableList = () => { | ||
const [items, setItems] = useState([]); | ||
|
||
const handleLoadItems = useCallback(async () => { | ||
try { | ||
const loadItems = () => | ||
new Promise((resolve) => { | ||
setTimeout(() => { | ||
resolve( | ||
Array.from( | ||
{length: 10}, | ||
(_item, index) => `Item ${Math.random() * 100 * (index + 1)}`, | ||
), | ||
); | ||
}, 1000); | ||
}); | ||
|
||
setItems(await loadItems()); | ||
} catch (error) { | ||
console.error(error); | ||
} | ||
}, []); | ||
|
||
return ( | ||
<> | ||
<ProgressButton onClick={handleLoadItems}>Load items</ProgressButton> | ||
<ul> | ||
{items.map((item) => ( | ||
<li key={item}>{item}</li> | ||
))} | ||
</ul> | ||
</> | ||
); | ||
}; | ||
``` |
16 changes: 16 additions & 0 deletions
16
src/hooks/useAsyncActionHandler/__stories__/ProgressButton.tsx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
import React from 'react'; | ||
|
||
import {Button, ButtonProps} from '../../../components'; | ||
import {useAsyncActionHandler} from '../useAsyncActionHandler'; | ||
|
||
export type ProgressButtonProps = { | ||
onClick: (event: React.MouseEvent<HTMLButtonElement>) => Promise<unknown>; | ||
} & Exclude<ButtonProps, 'onClick'>; | ||
|
||
export const ProgressButton = (props: ProgressButtonProps) => { | ||
const {onClick, loading: providedIsLoading} = props; | ||
|
||
const {isLoading, handler: handleClick} = useAsyncActionHandler({handler: onClick}); | ||
|
||
return <Button {...props} onClick={handleClick} loading={isLoading || providedIsLoading} />; | ||
}; |
3 changes: 3 additions & 0 deletions
3
src/hooks/useAsyncActionHandler/__stories__/UseAsyncActionHandlerDemo.classname.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
import {block} from '../../../components/utils/cn'; | ||
|
||
export const cnUseAsyncActionHandlerDemo = block('async-action-handler-demo'); |
11 changes: 11 additions & 0 deletions
11
src/hooks/useAsyncActionHandler/__stories__/UseAsyncActionHandlerDemo.scss
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
@import '../../../components/variables'; | ||
|
||
$block: '.#{$ns}async-action-handler-demo'; | ||
|
||
#{$block} { | ||
display: flex; | ||
flex-direction: column; | ||
align-items: flex-start; | ||
justify-content: flex-start; | ||
gap: 16px; | ||
} |
42 changes: 42 additions & 0 deletions
42
src/hooks/useAsyncActionHandler/__stories__/UseAsyncActionHandlerDemo.tsx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
import React from 'react'; | ||
|
||
import {ProgressButton} from './ProgressButton'; | ||
import {cnUseAsyncActionHandlerDemo} from './UseAsyncActionHandlerDemo.classname'; | ||
|
||
import './UseAsyncActionHandlerDemo.scss'; | ||
|
||
export const UseAsyncActionHandlerDemo = () => { | ||
const [items, setItems] = React.useState<string[]>([]); | ||
|
||
const handleLoadItems = React.useCallback(async () => { | ||
const loadItems = () => | ||
new Promise<string[]>((resolve) => { | ||
setTimeout(() => { | ||
resolve( | ||
Array.from( | ||
{length: 10}, | ||
(_item, index) => | ||
`Item ${Math.round(Math.random() * 100 * (index + 1))}`, | ||
), | ||
); | ||
}, 1000); | ||
}); | ||
|
||
try { | ||
setItems(await loadItems()); | ||
} catch (error) { | ||
console.error(error); | ||
} | ||
}, []); | ||
|
||
return ( | ||
<div className={cnUseAsyncActionHandlerDemo()}> | ||
<ProgressButton onClick={handleLoadItems}>Load items</ProgressButton> | ||
<ul> | ||
{items.map((item) => ( | ||
<li key={item}>{item}</li> | ||
))} | ||
</ul> | ||
</div> | ||
); | ||
}; |
11 changes: 11 additions & 0 deletions
11
src/hooks/useAsyncActionHandler/__stories__/UseAsyncActionHandlerStories.stories.tsx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
import React from 'react'; | ||
|
||
import type {Meta, StoryFn} from '@storybook/react'; | ||
|
||
import {UseAsyncActionHandlerDemo} from './UseAsyncActionHandlerDemo'; | ||
|
||
export default { | ||
title: 'Hooks/useAsyncActionHandler', | ||
} as Meta; | ||
|
||
export const Showcase: StoryFn = () => <UseAsyncActionHandlerDemo />; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
export * from './useAsyncActionHandler'; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
import React from 'react'; | ||
|
||
export interface UseAsyncActionHandlerProps<ActionResult = void> { | ||
handler: (...args: any[]) => Promise<ActionResult>; | ||
} | ||
|
||
export interface UseAsyncActionHandlerResult<Action = () => Promise<void>> { | ||
isLoading: boolean; | ||
handler: Action; | ||
} | ||
|
||
export function useAsyncActionHandler<ActionResult>({ | ||
handler, | ||
}: UseAsyncActionHandlerProps<ActionResult>): UseAsyncActionHandlerResult<typeof handler> { | ||
const mounted = React.useRef(true); | ||
const [isLoading, setLoading] = React.useState(false); | ||
|
||
React.useEffect(() => { | ||
mounted.current = true; | ||
|
||
return () => { | ||
mounted.current = false; | ||
}; | ||
}, []); | ||
|
||
const handleAction: typeof handler = React.useCallback( | ||
(...args) => { | ||
setLoading(true); | ||
|
||
const handlerResult = handler(...args); | ||
|
||
if (handlerResult instanceof Promise) { | ||
return handlerResult.finally(() => { | ||
if (mounted.current) { | ||
setLoading(false); | ||
} | ||
}); | ||
} | ||
|
||
if (process.env.NODE_ENV !== 'production') { | ||
// used only in dev build | ||
// eslint-disable-next-line no-console | ||
console.error( | ||
"@gravity-ui/uikit: (useAsyncActionHandler) the provided handler doesn't return a promise", | ||
); | ||
} | ||
|
||
setLoading(false); | ||
|
||
return handlerResult; | ||
}, | ||
[handler], | ||
); | ||
|
||
return { | ||
isLoading, | ||
handler: handleAction, | ||
}; | ||
} |