Skip to content

Commit

Permalink
Enhance query context handling for more maintainable code
Browse files Browse the repository at this point in the history
- Introduced `DEFAULT_QUERY_CONTEXT_ATTRIBUTES` in `edit.tsx` to maintain a clear list of default query context attributes.
- Modified `ProductTemplateEdit` to automatically include these default attributes in `queryContextIncludes`, ensuring they are always part of the query context without manual initialization.
- Simplified `useProductCollectionQueryContext` in `utils.tsx` by removing static initialization of 'collection' and 'id', relying instead on the dynamic addition of necessary attributes from `queryContextIncludes`.

This refactor enhances the maintainability and clarity of the code, ensuring a solid foundation for future enhancements and features.
  • Loading branch information
imanish003 committed Feb 7, 2024
1 parent 290600d commit d4f071d
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 8 deletions.
Expand Up @@ -27,6 +27,8 @@ import type { BlockEditProps, BlockInstance } from '@wordpress/blocks';
*/
import { useProductCollectionQueryContext } from './utils';

const DEFAULT_QUERY_CONTEXT_ATTRIBUTES = [ 'collection', 'id' ];

const ProductTemplateInnerBlocks = () => {
const innerBlocksProps = useInnerBlocksProps(
{ className: 'wc-block-product' },
Expand Down Expand Up @@ -163,6 +165,13 @@ const ProductTemplateEdit = ( {
isNumber
);

// Add default query context attributes to queryContextIncludes
queryContextIncludes = [
...new Set(
queryContextIncludes.concat( DEFAULT_QUERY_CONTEXT_ATTRIBUTES )
),
];

const productCollectionQueryContext = useProductCollectionQueryContext( {
clientId,
queryContextIncludes,
Expand Down
Expand Up @@ -62,16 +62,9 @@ export const useProductCollectionQueryContext = ( {
return null;
}

/**
* Initialize the query context object with collection and id attributes as
* they should always be included in the query context.
*/
const queryContext: {
[ key: string ]: unknown;
} = {
collection: productCollectionBlockAttributes?.collection,
id: productCollectionBlockAttributes?.id,
};
} = {};

if ( queryContextIncludes?.length ) {
queryContextIncludes.forEach( ( attribute: string ) => {
Expand Down

0 comments on commit d4f071d

Please sign in to comment.