@wordpress/core-data
Version:
Access to and manipulation of core WordPress entities.
65 lines (62 loc) • 2.13 kB
JavaScript
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = useEntityProp;
var _element = require("@wordpress/element");
var _data = require("@wordpress/data");
var _name = require("../name");
var _useEntityId = _interopRequireDefault(require("./use-entity-id"));
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Hook that returns the value and a setter for the
* specified property of the nearest provided
* entity of the specified type.
*
* @param {string} kind The entity kind.
* @param {string} name The entity name.
* @param {string} prop The property name.
* @param {number|string} [_id] An entity ID to use instead of the context-provided one.
*
* @return {[*, Function, *]} An array where the first item is the
* property value, the second is the
* setter and the third is the full value
* object from REST API containing more
* information like `raw`, `rendered` and
* `protected` props.
*/
function useEntityProp(kind, name, prop, _id) {
const providerId = (0, _useEntityId.default)(kind, name);
const id = _id !== null && _id !== void 0 ? _id : providerId;
const {
value,
fullValue
} = (0, _data.useSelect)(select => {
const {
getEntityRecord,
getEditedEntityRecord
} = select(_name.STORE_NAME);
const record = getEntityRecord(kind, name, id); // Trigger resolver.
const editedRecord = getEditedEntityRecord(kind, name, id);
return record && editedRecord ? {
value: editedRecord[prop],
fullValue: record[prop]
} : {};
}, [kind, name, id, prop]);
const {
editEntityRecord
} = (0, _data.useDispatch)(_name.STORE_NAME);
const setValue = (0, _element.useCallback)(newValue => {
editEntityRecord(kind, name, id, {
[prop]: newValue
});
}, [editEntityRecord, kind, name, id, prop]);
return [value, setValue, fullValue];
}
//# sourceMappingURL=use-entity-prop.js.map
;