Replace isBusy with new activity-state manager

This commit is contained in:
Philipp Stracker 2024-12-05 18:55:56 +01:00
parent 405c397331
commit 9786a18eb0
No known key found for this signature in database
5 changed files with 77 additions and 16 deletions

View file

@ -81,12 +81,34 @@ const useHooks = () => {
};
export const useBusyState = () => {
const { setIsBusy } = useDispatch( STORE_NAME );
const isBusy = useTransient( 'isBusy' );
const { startActivity, stopActivity } = useDispatch( STORE_NAME );
// Resolved value (object), contains a list of all running actions.
const activities = useSelect(
( select ) => select( STORE_NAME ).getActivityList(),
[]
);
// Derive isBusy state from activities
const isBusy = Object.keys( activities ).length > 0;
// HOC that starts and stops an activity while the callback is executed.
const withActivity = useCallback(
async ( id, description, asyncFn ) => {
startActivity( id, description );
try {
return await asyncFn();
} finally {
stopActivity( id );
}
},
[ startActivity, stopActivity ]
);
return {
isBusy,
setIsBusy: useCallback( ( busy ) => setIsBusy( busy ), [ setIsBusy ] ),
withActivity, // HOC
isBusy, // Boolean.
activities, // Object.
};
};