reactjs/rfcs

[Feature request] error handling in useTransition

vkurchatkin opened this issue · 1 comments

I propose adding the ability to handle errors in useTransition.

Example

const [startTransition, isPending] = useTransition({
    timeoutMs: 3000
 });

const [userId, setUserId] = React.useState();

const userInfo = readUserInfo(userIds);

function loadData() {
   startTransition((controller) => {
      setUserId('foo');

      return {
          onError: (err) => {
               alert('Failed to load user data!');
               controller.abort();
           }
      };
   }

Explanation

Callback object

The function that is passed to startTransition returns a callback object, that can be used to notify the caller about transition state changes. onError is called if the corresponding Suspense boundary caught and error while rendering this transition.

Controller object

The function that is passed to startTransition receives a controller object, that can be use to abort transition. controller.abort() can be called at any time before the transition is complete. If it is called when transition is pending, the whole suspended "branch" is discarded, as if the transition never started.

If controller.abort() is called in onError handler, this prevents the error from propagating to ErrorBoundary.

Motivation

So far the only way to handle data fetching error in Suspense is anErrorBoundary component. It usually means that on Error the whole chunk of UI disappears and a fallback is rendered. What if want to leave the old UI and just show an error message instead?

Of course, you could use componentDidCatch to catch an error and just render the same content as before the error (i.e. props.children). The problem is that ErrorBoundary lacks the knowledge required to handle the error properly. startTransition is the right place to provide all the necessary context since it corresponds directly to some user action.

Hi, thanks for your suggestion. RFCs should be submitted as pull requests, not issues. I will close this issue but feel free to resubmit in the PR format.