Skip to content

Another potential exercise 2 extra credit #128

@bruce-c-liu

Description

@bruce-c-liu

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],
  );

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions