mirror of
https://github.com/woocommerce/woocommerce-paypal-payments.git
synced 2025-09-10 04:59:07 +08:00
✨ Add gemeric hook-generator for data access
This commit is contained in:
parent
bd14ea441e
commit
f07d9bad82
2 changed files with 66 additions and 15 deletions
|
@ -1,3 +1,6 @@
|
|||
import { useDispatch, useSelect } from '@wordpress/data';
|
||||
import { useCallback } from '@wordpress/element';
|
||||
|
||||
/**
|
||||
* Updates an object with new values, filtering based on allowed keys.
|
||||
*
|
||||
|
@ -13,6 +16,10 @@ const updateObject = ( oldObject, newValues, allowedKeys = {} ) => ( {
|
|||
...Object.keys( newValues ).reduce( ( acc, key ) => {
|
||||
if ( key in allowedKeys ) {
|
||||
acc[ key ] = newValues[ key ];
|
||||
} else {
|
||||
console.warn(
|
||||
`Ignoring unknown key "${ key }" - to use it, add it to the initial store properties in the reducer.`
|
||||
);
|
||||
}
|
||||
return acc;
|
||||
}, {} ),
|
||||
|
@ -73,3 +80,57 @@ export const createReducer = (
|
|||
return state;
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns an object with two hooks:
|
||||
* - useTransient( prop )
|
||||
* - usePersistent( prop )
|
||||
*
|
||||
* Both hooks have a similar syntax to the native "useState( prop )" hook, but provide access to
|
||||
* a transient or persistent property in the relevant Redux store.
|
||||
*
|
||||
* Sample:
|
||||
*
|
||||
* const { useTransient } = createHooksForStore( STORE_NAME );
|
||||
* const [ isReady, setIsReady ] = useTransient( 'isReady' );
|
||||
*
|
||||
* @param {string} storeName Store name.
|
||||
* @return {{useTransient, usePersistent}} Store hooks.
|
||||
*/
|
||||
export const createHooksForStore = ( storeName ) => {
|
||||
const createHook = ( selector, dispatcher ) => ( key ) => {
|
||||
const value = useSelect(
|
||||
( select ) => {
|
||||
const store = select( storeName );
|
||||
if ( ! store?.[ selector ] ) {
|
||||
throw new Error(
|
||||
`Please create the selector "${ selector }" for store "${ storeName }"`
|
||||
);
|
||||
}
|
||||
return store[ selector ]()?.[ key ];
|
||||
},
|
||||
[ key ]
|
||||
);
|
||||
|
||||
const actions = useDispatch( storeName );
|
||||
|
||||
const setValue = useCallback(
|
||||
( newValue ) => {
|
||||
if ( ! actions?.[ dispatcher ] ) {
|
||||
throw new Error(
|
||||
`Please create the action "${ dispatcher }" for store "${ storeName }"`
|
||||
);
|
||||
}
|
||||
actions[ dispatcher ]( key, newValue );
|
||||
},
|
||||
[ actions, key ]
|
||||
);
|
||||
|
||||
return [ value, setValue ];
|
||||
};
|
||||
|
||||
return {
|
||||
useTransient: createHook( 'transientData', 'setTransient' ),
|
||||
usePersistent: createHook( 'persistentData', 'setPersistent' ),
|
||||
};
|
||||
};
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue