advanced-react-apis icon indicating copy to clipboard operation
advanced-react-apis copied to clipboard

Another potential exercise 2 extra credit

Open bruce-c-liu opened this issue 4 years ago • 2 comments
trafficstars

I noticed that when you click the pokemon names in rapid succession, it will load their info into view one by one as the requests resolve, which isn't great UX. So I came up with a way where only the most recent fetch matters, while earlier ones are ignored. This both improves the UX as well as handles race conditions.

  const safeDispatch = useSafeDispatch(dispatch);

  const mostRecentPromise = React.useRef(null);

  const run = React.useCallback(
    promise => {
      safeDispatch({ type: 'pending' });
      mostRecentPromise.current = promise;
      let action = {};
      promise
        .then(
          data => {
            action = { type: 'resolved', data };
          },
          error => {
            action = { type: 'rejected', error };
          },
        )
        .finally(() => {
          if (promise === mostRecentPromise.current) {
            safeDispatch(action);
          }
        });
    },
    [safeDispatch],
  );

bruce-c-liu avatar Mar 23 '21 16:03 bruce-c-liu

Yes, this would be a great addition to the workshop and I'll make sure to include it in the update 👍 Thank you!

kentcdodds avatar Mar 23 '21 17:03 kentcdodds

Awesome! I look forward to it.

bruce-c-liu avatar Mar 23 '21 17:03 bruce-c-liu