Created
August 29, 2023 04:10
-
-
Save mharj/8669f99900debf9c2bbed09f881c3364 to your computer and use it in GitHub Desktop.
useThunkDispatch()
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
| // export const useThunkDispatch = () => useDispatch<RootThunkDispatch>(); | |
| export function isPromise(action: unknown): action is Promise<unknown> { | |
| return typeof action === 'object' && 'catch' in (action as Promise<unknown>) && typeof (action as Promise<unknown>).catch === 'function'; | |
| } | |
| // hook action errors hook to component level and cause hook to throw component level error (=> to Error boundary) | |
| export function useThunkDispatch(): RootThunkDispatch { | |
| const dispatch = useDispatch<RootThunkDispatch>(); | |
| const [error, setError] = useState<unknown | undefined>(undefined); | |
| if (error) { | |
| throw error; | |
| } | |
| return useCallback( | |
| (action: Parameters<typeof dispatch>[0]) => { | |
| try { | |
| const ret = dispatch(action); | |
| if (isPromise(ret)) { | |
| ret.catch((e: unknown) => { | |
| setError(e); // hook error function to catch promise error | |
| }); | |
| } | |
| return ret; | |
| } catch (e) { | |
| setError(e); | |
| } | |
| }, | |
| [dispatch], | |
| ); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment