availity-react icon indicating copy to clipboard operation
availity-react copied to clipboard

Add async error handling hook

Open bjnewman opened this issue 1 year ago • 0 comments

🚀 Feature request

Current Behavior

We don't currently have any platform components to assist developers with error handling.

Desired Behavior

We should provide hooks and/or components that assist developers with error handling.

Suggested Solution

For example, in the common use case where devs need to handle errors during events and lifecycle hooks we should provide default hooks that surface async errors so they can be caught and handled by error boundaries rather than putting error handling logic in each component.

Something like import { useCallback, useState } from 'react'

/* Hook to get a callback function for throwing synchronous error from asynchronous code When this callback is used somewhere within an error boundary, it will trigger it, even if you are in an async block

const throwError = useGlobalError()
async function foo() { 
useEffect(async () => 
try {
 const resp = fetch('users') // throws on 403 response
 setResponse(resp)
} catch (e) {
throwError(e)
}
,[])

*/ export default function useGlobalError(): (e: Error) => void { const [, setError] = useState() return useCallback((e: Error) => { setError(() => { throw e }) }, []) }

Who does this impact? Who is this for?

All users

Describe alternatives you've considered

The react-error-boundary library exposes other utilities to help users handle errors, we could simply make a wrapper around that to let users know that it is a platform pattern they are expected to follow.

Additional context

Throwing inside of a setState was at one point Dan Abramov's recommended pattern for surfacing async errors. https://github.com/facebook/react/issues/14981#issuecomment-468460187

bjnewman avatar Apr 04 '23 21:04 bjnewman