@wordpress/data
Version:
Data module for WordPress.
63 lines (52 loc) • 2.15 kB
JavaScript
;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _element = require("@wordpress/element");
var _compose = require("@wordpress/compose");
var _useRegistry = _interopRequireDefault(require("../registry-provider/use-registry"));
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Custom react hook for returning aggregate dispatch actions using the provided
* dispatchMap.
*
* Currently this is an internal api only and is implemented by `withDispatch`
*
* @param {Function} dispatchMap Receives the `registry.dispatch` function as
* the first argument and the `registry` object
* as the second argument. Should return an
* object mapping props to functions.
* @param {Array} deps An array of dependencies for the hook.
* @return {Object} An object mapping props to functions created by the passed
* in dispatchMap.
*/
const useDispatchWithMap = (dispatchMap, deps) => {
const registry = (0, _useRegistry.default)();
const currentDispatchMap = (0, _element.useRef)(dispatchMap);
(0, _compose.useIsomorphicLayoutEffect)(() => {
currentDispatchMap.current = dispatchMap;
});
return (0, _element.useMemo)(() => {
const currentDispatchProps = currentDispatchMap.current(registry.dispatch, registry);
return Object.fromEntries(Object.entries(currentDispatchProps).map(_ref => {
let [propName, dispatcher] = _ref;
if (typeof dispatcher !== 'function') {
// eslint-disable-next-line no-console
console.warn(`Property ${propName} returned from dispatchMap in useDispatchWithMap must be a function.`);
}
return [propName, function () {
return currentDispatchMap.current(registry.dispatch, registry)[propName](...arguments);
}];
}));
}, [registry, ...deps]);
};
var _default = useDispatchWithMap;
exports.default = _default;
//# sourceMappingURL=use-dispatch-with-map.js.map