Skip to content

Stabilize result object #26

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 36 additions & 17 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
useLayoutEffect,
useRef,
useState,
useMemo,
} from 'react';

// See https://gist.github.com/gaearon/e7d97cdf38a2907924ea12e4ebdf3c85
Expand Down Expand Up @@ -287,15 +288,28 @@ const useAsyncInternal = <R = UnknownResult, Args extends any[] = UnknownArgs>(
}
}, params);

return {
...AsyncState.value,
set: AsyncState.set,
merge: AsyncState.merge,
reset: AsyncState.reset,
execute: executeAsyncOperation,
currentPromise: CurrentPromise.get(),
currentParams,
};
const currentPromise = CurrentPromise.get();

return useMemo(
() => ({
...AsyncState.value,
set: AsyncState.set,
merge: AsyncState.merge,
reset: AsyncState.reset,
execute: executeAsyncOperation,
currentPromise,
currentParams,
}),
[
AsyncState.value,
AsyncState.set,
AsyncState.merge,
AsyncState.reset,
executeAsyncOperation,
currentPromise,
currentParams,
]
);
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I noticed that AsyncState.value is never mutated, so the memo dependency is just .value itself.

};

// override to allow passing an async function with no args:
Expand Down Expand Up @@ -465,12 +479,17 @@ export const useAsyncFetchMore = <R, Args extends any[]>({
}
}, [shouldReset]);

return {
canFetchMore:
value.status === 'success' && fetchMoreAsync.status !== 'loading',
loading: fetchMoreAsync.loading,
status: fetchMoreAsync.status,
fetchMore: fetchMoreAsync.execute,
isEnd,
};
const canFetchMore =
value.status === 'success' && fetchMoreAsync.status !== 'loading';

return useMemo(
() => ({
canFetchMore,
loading: fetchMoreAsync.loading,
status: fetchMoreAsync.status,
fetchMore: fetchMoreAsync.execute,
isEnd,
}),
[canFetchMore, fetchMoreAsync, isEnd]
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fetchMoreAsync is memoized so no need to check for its individual methods.

);
};