Created
August 9, 2024 12:37
-
-
Save mharj/14616a611908d253a8002a3b040d5caf to your computer and use it in GitHub Desktop.
redux hooks?
This file contains hidden or 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
| import {useCallback, useState} from 'react'; | |
| import {Action, ActionCreator} from '@reduxjs/toolkit'; | |
| import {ThunkResult, useThunkDispatch} from '../redux/reducers'; | |
| export function useThunkAction<AC extends ActionCreator<ThunkResult<unknown>>, RT extends Awaited<ReturnType<ReturnType<AC>>>>( | |
| actionCreator: AC, | |
| ): [(...args: Parameters<AC>) => Promise<RT>, boolean] { | |
| const [isActionRunning, setRunning] = useState(false); | |
| const dispatch = useThunkDispatch(); | |
| const action = useCallback( | |
| async (...args: Parameters<AC>): Promise<RT> => { | |
| setRunning(true); | |
| try { | |
| return (await dispatch(actionCreator(...args))) as RT; | |
| } finally { | |
| setRunning(false); | |
| } | |
| }, | |
| [actionCreator, dispatch], | |
| ); | |
| return [action, isActionRunning]; | |
| } | |
| export function useAction<A extends Action<unknown>>(actionCreator: ActionCreator<A>): (...args: Parameters<ActionCreator<A>>) => A { | |
| const dispatch = useThunkDispatch(); | |
| return useCallback((...args: Parameters<ActionCreator<A>>): A => dispatch(actionCreator(...args)), [actionCreator, dispatch]); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment