mirror of
https://github.com/woocommerce/woocommerce-paypal-payments.git
synced 2025-09-01 07:02:48 +08:00
✨ Add new activity observer hook
This commit is contained in:
parent
e88622591e
commit
88d96f8965
1 changed files with 50 additions and 2 deletions
|
@ -8,7 +8,7 @@
|
|||
*/
|
||||
|
||||
import { useDispatch, useSelect } from '@wordpress/data';
|
||||
import { useCallback } from '@wordpress/element';
|
||||
import { useCallback, useEffect, useState } from '@wordpress/element';
|
||||
|
||||
import { createHooksForStore } from '../utils';
|
||||
import { STORE_NAME } from './constants';
|
||||
|
@ -208,6 +208,54 @@ export const useBusyState = () => {
|
|||
return {
|
||||
withActivity, // HOC
|
||||
isBusy, // Boolean.
|
||||
activities, // Object.
|
||||
};
|
||||
};
|
||||
|
||||
export const useActivityObserver = () => {
|
||||
const activities = useSelect(
|
||||
( select ) => select( STORE_NAME ).getActivityList(),
|
||||
[]
|
||||
);
|
||||
|
||||
const [ prevActivities, setPrevActivities ] = useState( activities );
|
||||
|
||||
useEffect( () => {
|
||||
setPrevActivities( activities );
|
||||
}, [ activities ] );
|
||||
|
||||
const onStarted = useCallback(
|
||||
( callback ) => {
|
||||
const newActivities = Object.keys( activities ).filter(
|
||||
( id ) => ! prevActivities[ id ]
|
||||
);
|
||||
if ( ! newActivities.length ) {
|
||||
return;
|
||||
}
|
||||
newActivities.forEach( ( id ) =>
|
||||
callback( id, Object.keys( activities ) )
|
||||
);
|
||||
},
|
||||
[ activities, prevActivities ]
|
||||
);
|
||||
|
||||
const onFinished = useCallback(
|
||||
( callback ) => {
|
||||
const finishedActivities = Object.keys( prevActivities ).filter(
|
||||
( id ) => ! activities[ id ]
|
||||
);
|
||||
if ( ! finishedActivities.length ) {
|
||||
return;
|
||||
}
|
||||
finishedActivities.forEach( ( id ) =>
|
||||
callback( id, Object.keys( activities ) )
|
||||
);
|
||||
},
|
||||
[ activities, prevActivities ]
|
||||
);
|
||||
|
||||
return {
|
||||
activities,
|
||||
onStarted,
|
||||
onFinished,
|
||||
};
|
||||
};
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue