Skip to content

Instantly share code, notes, and snippets.

@mharj
Created August 29, 2023 04:10
Show Gist options
  • Select an option

  • Save mharj/8669f99900debf9c2bbed09f881c3364 to your computer and use it in GitHub Desktop.

Select an option

Save mharj/8669f99900debf9c2bbed09f881c3364 to your computer and use it in GitHub Desktop.
useThunkDispatch()
// 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