Skip to content

Commit

Permalink
Switch to the useEntityRecord hook
Browse files Browse the repository at this point in the history
  • Loading branch information
glendaviesnz committed Nov 30, 2022
1 parent b978c6e commit 5aa39cd
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 19 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
*/
import { useEffect } from '@wordpress/element';
import { useSelect, useDispatch } from '@wordpress/data';
import { store as coreStore } from '@wordpress/core-data';
import { useEntityRecord } from '@wordpress/core-data';

/**
* Internal dependencies
Expand All @@ -19,10 +19,9 @@ function useGlobalStylesRenderer() {
const [ styles, settings, svgFilters ] = useGlobalStylesOutput();
const { getSettings } = useSelect( editSiteStore );
const { updateSettings } = useDispatch( editSiteStore );
const customCSS = useSelect( ( select ) => {
const { getEntityRecord } = select( coreStore );
return getEntityRecord( 'postType', 'custom_css' )?.post_content;
} );

const { record } = useEntityRecord( 'postType', 'custom_css' );
const customCSS = record?.post_content;

useEffect( () => {
if ( ! styles || ! settings ) {
Expand Down
36 changes: 22 additions & 14 deletions packages/edit-site/src/components/global-styles/custom-css.js
Original file line number Diff line number Diff line change
@@ -1,39 +1,47 @@
/**
* WordPress dependencies
*/
import { useState } from '@wordpress/element';
import { useState, useEffect } from '@wordpress/element';
import { TextareaControl, Button } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import { useSelect, useDispatch } from '@wordpress/data';
import { store as coreStore } from '@wordpress/core-data';
import { useEntityRecord } from '@wordpress/core-data';

function CustomCSSControl() {
const [ updatedCSS, updateCSS ] = useState();
const customCSS = useSelect( ( select ) => {
const { getEntityRecord } = select( coreStore );
return getEntityRecord( 'postType', 'custom_css' )?.post_content;
} );
const [ customCSS, updateCSS ] = useState();
const { record, hasResolved, edit, save } = useEntityRecord(
'postType',
'custom_css'
);

const { saveEntityRecord } = useDispatch( coreStore );
useEffect( () => {
if ( hasResolved ) {
updateCSS( record?.post_content );
}
}, [ hasResolved, record ] );

function updateCustomCSS() {
saveEntityRecord( 'postType', 'custom_css', {
custom_css: updatedCSS,
edit( {
custom_css: customCSS,
} );
save();
}

if ( ! hasResolved ) {
return __( 'Loading' );
}

return (
<>
<TextareaControl
value={ updatedCSS || customCSS }
value={ customCSS }
onChange={ ( value ) => updateCSS( value ) }
/>
<Button
isPrimary
onClick={ () => updateCustomCSS() }
label={ __( 'Update' ) }
label={ __( 'Save' ) }
>
{ __( 'Update' ) }
{ __( 'Save' ) }
</Button>
</>
);
Expand Down

0 comments on commit 5aa39cd

Please sign in to comment.