Skip to content
This repository has been archived by the owner on Feb 23, 2024. It is now read-only.

POC: Update preview on editor side with action #7043

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion assets/js/blocks/product-query/inspector-controls.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@
import { __ } from '@wordpress/i18n';
import { InspectorControls } from '@wordpress/block-editor';
import { ToggleControl } from '@wordpress/components';
import { addFilter } from '@wordpress/hooks';
import { addFilter, doAction } from '@wordpress/hooks';
import { EditorBlock } from '@woocommerce/types';
import { ElementType } from 'react';
import apiFetch from '@wordpress/api-fetch';

/**
* Internal dependencies
Expand All @@ -27,6 +28,17 @@ export const INSPECTOR_CONTROLS = {
}
onChange={ ( onSale ) => {
setCustomQueryAttribute( props, { onSale } );
apiFetch( {
path: '/wc/store/v1/products?on_sale=true',
} ).then( ( data ) => {
doAction(
'hook_name',
data?.map( ( product ) => ( {
...product,
type: 'product',
} ) )
);
} );
} }
/>
),
Expand Down
42 changes: 42 additions & 0 deletions assets/js/blocks/product-query/utils.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
/**
* External dependencies
*/

import apiFetch from '@wordpress/api-fetch';
import { doAction } from '@wordpress/hooks';

/**
* Internal dependencies
*/
Expand Down Expand Up @@ -52,3 +59,38 @@ export function setCustomQueryAttribute(
},
} );
}

const getQueryArgumentsByCustomQuery = ( customQuery: string ) => {
switch ( customQuery ) {
case 'onSale':
return 'on_sale=true';

default:
return '';
}
};

export async function fetchAndRenderProducts( props: ProductQueryBlock ) {
const customQueries = Object.entries(
props.attributes.__woocommerceVariationProps.attributes?.query || {}
);

const queryArguments = customQueries.reduce( ( acc, [ key, value ] ) => {
if ( value ) {
return acc.concat( getQueryArgumentsByCustomQuery( key ) );
}
return acc;
}, '' );

const products = await apiFetch( {
path: `/wc/store/v1/products?${ queryArguments }`,
} );

doAction(
'hook_name',
products?.map( ( product ) => ( {
...product,
type: 'product',
} ) )
);
}