UNPKG

@wordpress/core-data

Version:
8 lines (7 loc) 2.84 kB
{ "version": 3, "sources": ["../../src/hooks/use-entity-prop.js"], "sourcesContent": ["/**\n * WordPress dependencies\n */\nimport { useCallback } from '@wordpress/element';\nimport { useDispatch, useSelect } from '@wordpress/data';\n\n/**\n * Internal dependencies\n */\nimport { STORE_NAME } from '../name';\nimport useEntityId from './use-entity-id';\n\n/**\n * Hook that returns the value and a setter for the\n * specified property of the nearest provided\n * entity of the specified type.\n *\n * @param {string} kind The entity kind.\n * @param {string} name The entity name.\n * @param {string} prop The property name.\n * @param {number|string} [_id] An entity ID to use instead of the context-provided one.\n *\n * @return {[*, Function, *]} An array where the first item is the\n * property value, the second is the\n * setter and the third is the full value\n * \t\t\t\t\t\t\t object from REST API containing more\n * \t\t\t\t\t\t\t information like `raw`, `rendered` and\n * \t\t\t\t\t\t\t `protected` props.\n */\nexport default function useEntityProp( kind, name, prop, _id ) {\n\tconst providerId = useEntityId( kind, name );\n\tconst id = _id ?? providerId;\n\n\tconst { value, fullValue } = useSelect(\n\t\t( select ) => {\n\t\t\tconst { getEntityRecord, getEditedEntityRecord } =\n\t\t\t\tselect( STORE_NAME );\n\t\t\tconst record = getEntityRecord( kind, name, id ); // Trigger resolver.\n\t\t\tconst editedRecord = getEditedEntityRecord( kind, name, id );\n\t\t\treturn record && editedRecord\n\t\t\t\t? {\n\t\t\t\t\t\tvalue: editedRecord[ prop ],\n\t\t\t\t\t\tfullValue: record[ prop ],\n\t\t\t\t }\n\t\t\t\t: {};\n\t\t},\n\t\t[ kind, name, id, prop ]\n\t);\n\tconst { editEntityRecord } = useDispatch( STORE_NAME );\n\tconst setValue = useCallback(\n\t\t( newValue ) => {\n\t\t\teditEntityRecord( kind, name, id, {\n\t\t\t\t[ prop ]: newValue,\n\t\t\t} );\n\t\t},\n\t\t[ editEntityRecord, kind, name, id, prop ]\n\t);\n\n\treturn [ value, setValue, fullValue ];\n}\n"], "mappings": ";AAGA,SAAS,mBAAmB;AAC5B,SAAS,aAAa,iBAAiB;AAKvC,SAAS,kBAAkB;AAC3B,OAAO,iBAAiB;AAmBT,SAAR,cAAgC,MAAM,MAAM,MAAM,KAAM;AAC9D,QAAM,aAAa,YAAa,MAAM,IAAK;AAC3C,QAAM,KAAK,OAAO;AAElB,QAAM,EAAE,OAAO,UAAU,IAAI;AAAA,IAC5B,CAAE,WAAY;AACb,YAAM,EAAE,iBAAiB,sBAAsB,IAC9C,OAAQ,UAAW;AACpB,YAAM,SAAS,gBAAiB,MAAM,MAAM,EAAG;AAC/C,YAAM,eAAe,sBAAuB,MAAM,MAAM,EAAG;AAC3D,aAAO,UAAU,eACd;AAAA,QACA,OAAO,aAAc,IAAK;AAAA,QAC1B,WAAW,OAAQ,IAAK;AAAA,MACxB,IACA,CAAC;AAAA,IACL;AAAA,IACA,CAAE,MAAM,MAAM,IAAI,IAAK;AAAA,EACxB;AACA,QAAM,EAAE,iBAAiB,IAAI,YAAa,UAAW;AACrD,QAAM,WAAW;AAAA,IAChB,CAAE,aAAc;AACf,uBAAkB,MAAM,MAAM,IAAI;AAAA,QACjC,CAAE,IAAK,GAAG;AAAA,MACX,CAAE;AAAA,IACH;AAAA,IACA,CAAE,kBAAkB,MAAM,MAAM,IAAI,IAAK;AAAA,EAC1C;AAEA,SAAO,CAAE,OAAO,UAAU,SAAU;AACrC;", "names": [] }