useIsHasAttribute.js
2 years ago
useMetaState.js
2 years ago
useRepeaterState.js
2 years ago
useSelectPostMeta.js
2 years ago
useStateLoadingClasses.js
2 years ago
useStateValidClasses.js
2 years ago
useSuccessNotice.js
2 years ago
withSelectFormFields.js
2 years ago
useMetaState.js
46 lines
| 1 | const { |
| 2 | useSelect, |
| 3 | useDispatch, |
| 4 | } = wp.data; |
| 5 | |
| 6 | function useMetaState( |
| 7 | key, |
| 8 | ifEmpty = '{}', |
| 9 | dependencies = undefined, |
| 10 | ) { |
| 11 | const meta = useSelect( ( select ) => { |
| 12 | const rawMeta = select( 'core/editor' ).getEditedPostAttribute( 'meta' ) || {}; |
| 13 | |
| 14 | return JSON.parse( rawMeta[ key ] || ifEmpty ); |
| 15 | }, dependencies ); |
| 16 | |
| 17 | const { editPost } = useDispatch( 'core/editor' ); |
| 18 | |
| 19 | const setMetaStateValue = callable => { |
| 20 | let value; |
| 21 | |
| 22 | if ( 'function' === typeof callable ) { |
| 23 | value = callable( meta ); |
| 24 | } |
| 25 | else { |
| 26 | value = callable; |
| 27 | } |
| 28 | |
| 29 | if ( 'object' !== typeof value || null === value ) { |
| 30 | value = JSON.parse( ifEmpty ); |
| 31 | } |
| 32 | |
| 33 | editPost( { |
| 34 | meta: ( |
| 35 | { |
| 36 | ...meta, |
| 37 | [ key ]: JSON.stringify( value ), |
| 38 | } |
| 39 | ), |
| 40 | } ); |
| 41 | }; |
| 42 | |
| 43 | return [ meta, setMetaStateValue ]; |
| 44 | } |
| 45 | |
| 46 | export default useMetaState; |