index.js (2080B)
1 const {apiFetch} = wp; 2 const {useState} = wp.element; 3 const {compose} = wp.compose; 4 const {withDispatch, withSelect} = wp.data; 5 const {parse} = wp.blocks; 6 7 import {BlockPreview} from '@wordpress/block-editor'; 8 import {installedBlocksTypes} from '~redux-templates/stores/actionHelper'; 9 import './style.scss' 10 11 function BackgroundImage(props) { 12 const {data, appendErrorMessage, activeItemType} = props; 13 const [dataLoaded, setDataLoaded] = useState(false); 14 const [blocks, setBlocks] = useState(null); 15 16 if (data && dataLoaded === false) { 17 const type = activeItemType === 'section' ? 'sections' : 'pages'; 18 let the_url = 'redux/v1/templates/template?type=' + type + '&id=' + data.id + '&uid=' + window.userSettings.uid; 19 if ('source' in data) { 20 the_url += '&source=' + data.source; 21 } 22 23 const options = { 24 method: 'GET', 25 path: the_url, 26 headers: {'Content-Type': 'application/json', 'Registered-Blocks': installedBlocksTypes()} 27 }; 28 29 apiFetch(options).then(response => { 30 if (response.success) { 31 setBlocks(response.data); 32 } else { 33 appendErrorMessage(response.data.error); 34 } 35 setDataLoaded(true); 36 }).catch(error => { 37 appendErrorMessage(error.code + ' : ' + error.message); 38 setDataLoaded(true); 39 }); 40 } 41 42 if (dataLoaded === true) { 43 let parsed = parse(blocks.template); 44 return ( 45 <div> 46 <BlockPreview blocks={parsed} /> 47 </div> 48 ); 49 } 50 return null; 51 } 52 53 export default compose([ 54 withDispatch((dispatch) => { 55 const { 56 appendErrorMessage 57 } = dispatch('redux-templates/sectionslist'); 58 59 return { 60 appendErrorMessage 61 }; 62 }), 63 withSelect((select) => { 64 const {getActiveItemType} = select('redux-templates/sectionslist'); 65 return { 66 activeItemType: getActiveItemType() 67 }; 68 }) 69 ])(BackgroundImage);