advanced-react-apis
advanced-react-apis copied to clipboard
Another potential exercise 2 extra credit
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],
);
Yes, this would be a great addition to the workshop and I'll make sure to include it in the update 👍 Thank you!
Awesome! I look forward to it.