Skip to content

Limit the number of requests for products in Editor - #60863

Merged
kmanijak merged 5 commits into
trunkfrom
fix/52960-limit-excessive-product-requests
Sep 15, 2025
Merged

kmanijak merged 5 commits into
trunkfrom
fix/52960-limit-excessive-product-requests

Conversation

@kmanijak

@kmanijak kmanijak commented Sep 10, 2025 •

Copy link
Copy Markdown
Contributor

Submission Review Guidelines:

Changes proposed in this Pull Request:

Product Collection was using withProduct HOC that has no caching and that had terrible effect on Editor when viewing All Templates (and similar views presenting many templates) resulting in product requests for each product in each preview.

Also, we're doing another set of requests for each product since we're migrating product elements to new data source (via @wordpress/core-data). This one is cached and shared between previews so only happens once.

This PR makes the Product Collection rely on useStoreProduct hook inside of withProductDataContext HOC that was skipped due to always relying on withProduct. The useStoreProduct is cached so only single request per product happens across previews.

In practical example, let's say we had 5 instances of Product Collection displaying 30 products each.

Was: 5 blocks * 30 requests from withProduct + 30 from core-data = 180 requests
Is: 30 requests from useStoreProduct + 30 from core-data = 60 requests.

Overall:
N - Product Collection nblocks
M - products

Was: N * M + M requests
Is: 2 * M requests

The more templates (and template parts!), the more gains.

Practical test:

  • no posts with Product Collection block (they may be rendered in Blog Home!)
  • Product Collection with 30 products in Product Catalog
  • this is propagated to other templates:
    • Products by Category
    • Products by Tag
    • Products by Attribute
    • All Archives
    • Blog Home
    • ...
  • browser cache disabled
Case Before After Comment
All requests 2373 2326
Search: products Fetch/XHR requests 118 86 It's not 60 as expected theoretically since this also includes some "Related Products" requests and other requests including products keyword but the diff is signifcant
Search: specific product id Fetch/XHR requests image image Multiple instances calling for product + 1, reduced to 2 calls for whole editor
Lighthouse report image image This is obviously very individual depending on the templates, used blocks, etc. and cannot be taken as a reference to say performance was improved by X%

Note: keep in mind we need withProduct still if Product Collection is used within Single Product block but that's acceptable since it's much more rare case.

Closes #60795
Closes #52960

(For Bug Fixes) Bug introduced in PR # .

Screenshots or screen recordings:

Before After

How to test the changes in this Pull Request:

Using the WooCommerce Testing Instructions Guide, include your detailed testing instructions:

Product Collection - performance gain

  1. Make sure you use Product Collection in Product Catalog and other similar templates (e.g. Products by Category/Tags/Attributes)
  2. Go to Editor > All Templates
  3. Check browser dev tools Network and filter for products
  4. Choose some product id and filter for it
  5. Expected: Make sure there are only 2 requests for it (on trunk there should be multiple)

Note: it is possible there is some more if you use Single Product block somewhere on your pages. Some other blocks may do some other request as well, then check other product id. But the rule of thumb is we're looking for 2 requests coming from Product Collection.

Product Collection - correct data displayed

  1. Create new post
  2. Insert Product Collection
  3. Choose some collection
  4. Add some additional blocks, like Products SKU, Product Stock Indicator, Product Rating
  5. Expected: Make sure all data is displayed: image, price, sku, stock indicator, rating, sale badge
  6. Save and verify the frontend works

Single Product + Product Collection

  1. Create new post
  2. Insert Product block
  3. Choose some product
  4. Expected: Make sure all data is displayed: image, price, summary, etc.
  5. Insert Product Collection inside Product block
  6. Choose some collection
  7. Expected: Make sure products have their own data displayed rather than displaying data of product from Product block (see this PR to understand: Fix incorrect product data displayed in Product Collection in context of Single Product block #44123)

Legacy - All Products

  1. Create new post
  2. Insert All Products via Code Editor
  3. Exit Code Editor
  4. Expected: Make sure all data is displayed: image, price, sku, stock indicator, rating, sale badge
  5. Save and verify the frontend works

Legacy - Product (Beta)

  1. Go to Editor > Product Catalog
  2. Insert Products (Beta) via Code Editor
  3. Exit Code Editor
  4. Expected: Make sure all data is displayed: image, price, sku, stock indicator, rating, sale badge
  5. Save and verify the frontend works

Testing that has already taken place:

Changelog entry

  • Automatically create a changelog entry from the details below.
  • This Pull Request does not require a changelog entry. (Comment required below)
Changelog Entry Details

Significance

  • Patch
  • Minor
  • Major

Type

  • Fix - Fixes an existing bug
  • Add - Adds functionality
  • Update - Update existing functionality
  • Dev - Development related task
  • Tweak - A minor adjustment to the codebase
  • Performance - Address performance issues
  • Enhancement - Improvement to existing functionality

Message

Changelog Entry Comment

Comment

@github-actions github-actions Bot added the plugin: woocommerce Issues related to the WooCommerce Core plugin. label Sep 10, 2025
@kmanijak kmanijak changed the title Limit the product requests in editor Limit the number of requests for products in Editor Sep 11, 2025
@kmanijak
kmanijak marked this pull request as ready for review September 11, 2025 09:07
@woocommercebot
woocommercebot requested review from a team and dinhtungdu and removed request for a team September 11, 2025 09:07
@github-actions

github-actions Bot commented Sep 11, 2025 •

Copy link
Copy Markdown
Contributor

Testing Guidelines

Hi @gigitux @dinhtungdu ,

Apart from reviewing the code changes, please make sure to review the testing instructions (Guide) and verify that relevant tests (E2E, Unit, Integration, etc.) have been added or updated as needed.

Reminder: PR reviewers are required to document testing performed. This includes:

  • 🖼️ Screenshots or screen recordings.
  • 📝 List of functionality tested / steps followed.
  • 🌐 Site details (environment attributes such as hosting type, plugins, theme, store size, store age, and relevant settings).
  • 🔍 Any analysis performed, such as assessing potential impacts on environment attributes and other plugins, conducting performance profiling, or using LLM/AI-based analysis.

⚠️ Within the testing details you provide, please ensure that no sensitive information (such as API keys, passwords, user data, etc.) is included in this public issue.

@kmanijak
kmanijak requested a review from gigitux September 11, 2025 09:08
@github-actions

github-actions Bot commented Sep 11, 2025 •

Copy link
Copy Markdown
Contributor

Size Change: +97 B (0%)

Total Size: 5.84 MB

compressed-size-action

@github-actions

github-actions Bot commented Sep 11, 2025 •

Copy link
Copy Markdown
Contributor

Test using WordPress Playground

The changes in this pull request can be previewed and tested using a WordPress Playground instance.
WordPress Playground is an experimental project that creates a full WordPress instance entirely within the browser.

Test this pull request with WordPress Playground.

Note that this URL is valid for 30 days from when this comment was last updated. You can update it by closing/reopening the PR or pushing a new commit.

@coderabbitai

coderabbitai Bot commented Sep 11, 2025

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Adds a changelog entry and updates editor block logic to limit unnecessary product data requests by conditionally wiring product data. Introduces an experimental REST API flag in the Price block, splits Product Template rendering into data-wired vs non-wired paths based on context, and refines product ID selection in the product data HOC.

Changes

Cohort / File(s) Summary
Changelog
plugins/woocommerce/changelog/fix-52960-limit-excessive-product-requests
New changelog entry noting a patch-level performance change: Product Collection limits product data requests in the Editor.
Price block: experimental REST API gating
plugins/woocommerce/client/blocks/assets/js/atomic/blocks/product-elements/price/edit.tsx
Caches isExperimentalWcRestApiV4Enabled() result; conditionally renders Block with/without product and admin context based on the flag; adds fallback comment for legacy data path.
Product template data wiring split
plugins/woocommerce/client/blocks/assets/js/blocks/product-template/edit.tsx
Splits ProductContent into two variants: non-data-wired and withProduct-wired. Selects variant at runtime based on being inside woocommerce/single-product. Removes product/isLoading from props of the non-wired component.
Product data context ID selection
plugins/woocommerce/client/blocks/assets/js/shared/hocs/with-product-data-context.js
Adds getProductId(isDescendentOfQueryLoop, productId, postId) and uses it to compute fetch ID, preferring postId for query-loop descendants and falling back to postId when productId is absent.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant E as Editor (Gutenberg)
  participant PT as ProductTemplate (edit.tsx)
  participant PC as ProductContent / ProductContentWithProduct
  participant H as withProduct / ProductDataContextProvider
  participant API as REST API

  E->>PT: Render Product Template editor
  PT->>PT: Detect parent is 'woocommerce/single-product'?
  alt Inside Single Product
    PT->>PC: Use ProductContentWithProduct
    PC->>H: Wrap with ProductDataContextProvider
    H->>API: Fetch product by computed id
    API-->>H: Product data
    H-->>PC: Provide product context
    PC-->>E: Render inner blocks with product data
  else Not inside Single Product
    PT->>PC: Use ProductContent (no data wiring)
    PC-->>E: Render inner blocks without product data
  end
Loading
sequenceDiagram
  autonumber
  participant B as Price Block (edit.tsx)
  participant FF as Feature Flag
  participant API as REST API (v4 experimental)
  Note over B,FF: On mount, evaluate isExperimentalWcRestApiV4Enabled() once
  B->>FF: Check experimental API flag
  alt Flag enabled
    B->>B: Render with product + isAdmin=true
    B->>API: Use experimental data path
  else Flag disabled
    B->>B: Render without product + isAdmin=false
    Note over B: Legacy/fallback path (old fetching)
  end
Loading
sequenceDiagram
  autonumber
  participant H as with-product-data-context.js
  participant Q as Query Loop Context
  participant API as REST API
  H->>Q: Read isDescendentOfQueryLoop, productId, postId
  H->>H: id = getProductId(isDescendentOfQueryLoop, productId, postId)
  H->>API: Fetch product by id
  API-->>H: Product data
  H-->>Caller: Provide ProductDataContext
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Pre-merge checks (5 passed)

✅ Passed checks (5 passed)
Check name Status Explanation
Title Check ✅ Passed The title "Limit the number of requests for products in Editor" concisely and accurately summarizes the PR's primary purpose—reducing duplicate product fetches in the Site Editor by changing how Product Collection obtains product data. It is specific, concise, and directly related to the changes described in the diff and PR description.
Linked Issues Check ✅ Passed The changes directly address #52960 by consolidating product loading through a cached hook (useStoreProduct) so Product Collection no longer issues per-instance uncached requests, and they also target the symptom reported in #60795 by materially reducing editor-originating product requests that can drive high execution counts; the PR preserves withProduct for single-product contexts and includes test steps and a changelog entry to aid verification. Final confirmation of reduced host execution counts requires runtime validation, but the implemented approach matches the linked issues' objectives.
Out of Scope Changes Check ✅ Passed Reviewed file summaries and the changelog entry; all modifications (ProductContent split, with-product-data-context id logic, price component feature-flag caching, and the changelog) are consistent with the goal of reducing duplicate product requests in the editor and appear in-scope. I do not see unrelated or extraneous changes introduced in the provided summaries.
Description Check ✅ Passed The PR description is detailed and directly tied to the changeset: it explains the performance problem, the technical approach (moving Product Collection to cached useStoreProduct via withProductDataContext), testing steps, and the linked issues, so it is clearly related to the code changes.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.

Tip

👮 Agentic pre-merge checks are now available in preview!

Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.

  • Built-in checks – Quickly apply ready-made checks to enforce title conventions, require pull request descriptions that follow templates, validate linked issues for compliance, and more.
  • Custom agentic checks – Define your own rules using CodeRabbit’s advanced agentic capabilities to enforce organization-specific policies and workflows. For example, you can instruct CodeRabbit’s agent to verify that API documentation is updated whenever API schema files are modified in a PR. Note: Upto 5 custom checks are currently allowed during the preview period. Pricing for this feature will be announced in a few weeks.

Please see the documentation for more information.

Example:

reviews:
  pre_merge_checks:
    custom_checks:
      - name: "Undocumented Breaking Changes"
        mode: "warning"
        instructions: |
          Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).

Please share your feedback with us on this Discord post.

✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/52960-limit-excessive-product-requests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (7)
plugins/woocommerce/changelog/fix-52960-limit-excessive-product-requests (1)

1-5: Fix changelog format: add Comment key and remove stray character.

Woo changelog parser expects a Comment field; a bare line plus a dangling "5" will likely fail validation.

Apply:

 Significance: patch
 Type: performance

-Product Collection: limit the number of requests for product data in Editor
-5
+Comment: Product Collection: limit the number of requests for product data in the Editor
plugins/woocommerce/client/blocks/assets/js/atomic/blocks/product-elements/price/edit.tsx (2)

34-36: Context type missing postId.

PriceEdit uses context.postId (Line 80) but Context declares only queryId. This breaks type-safety and can fail TS builds.

Apply:

-interface Context {
-	queryId: number;
-}
+interface Context {
+	queryId?: number;
+	postId?: number;
+}

27-32: Align Attributes with stored flags.

You set isDescendentOfQueryLoop and isDescendentOfSingleProductTemplate via setAttributes, but they’re not in Attributes. Add them to avoid implicit any and improve editor state stability.

 interface Attributes {
 	textAlign: 'left' | 'center' | 'right';
-	isDescendentOfSingleProduct: boolean;
-	isDescendentOfSingleProductBlock: boolean;
-	productId: number;
+	isDescendentOfSingleProduct?: boolean;
+	isDescendentOfSingleProductBlock?: boolean;
+	isDescendentOfSingleProductTemplate?: boolean;
+	isDescendentOfQueryLoop?: boolean;
+	productId?: number;
 }
plugins/woocommerce/client/blocks/assets/js/blocks/product-template/edit.tsx (4)

89-99: Fix type mismatches: productId/postId should be numbers.

They are numbers in practice (from REST responses), but typed as strings. This later causes equality checks to fail.

 type ProductContentProps = {
-	attributes: { productId: string };
+	attributes: { productId: number };
 	displayTemplate: boolean;
 	blocks: BlockInstance[];
 	blockContext: {
 		postType: string;
-		postId: string;
+		postId: number;
 	};
 	setActiveBlockContextId: ( id: string ) => void;
 };

122-158: Type ProductContentWithProduct to remove ts-ignore at call site.

Cast HOC output to a component that accepts ProductContentProps.

-const ProductContentWithProduct = withProduct(
+const ProductContentWithProduct = ( withProduct(
 	( {
 		isLoading,
 		product,
 		displayTemplate,
 		blocks,
 		blockContext,
 		setActiveBlockContextId,
 	}: ProductContentProps & {
 		isLoading: boolean;
 		product: ProductResponseItem;
 	} ) => {
 		return (
 			<BlockContextProvider
 				key={ blockContext.postId }
 				value={ blockContext }
 			>
 				<ProductDataContextProvider
 					product={ product }
 					isLoading={ isLoading }
 				>
 					{ displayTemplate ? <ProductTemplateInnerBlocks /> : null }
 					<MemoizedProductTemplateBlockPreview
 						blocks={ blocks }
 						blockContextId={ blockContext.postId }
 						setActiveBlockContextId={ setActiveBlockContextId }
 						isHidden={ displayTemplate }
 					/>
 				</ProductDataContextProvider>
 			</BlockContextProvider>
 		);
 	}
-) );
+) ) as unknown as ( props: ProductContentProps ) => JSX.Element;

236-239: Use numeric state for activeBlockContextId.

It holds product IDs (numbers). The current string type causes === comparisons to fail later.

-const [ activeBlockContextId, setActiveBlockContextId ] =
-	useState< string >();
+const [ activeBlockContextId, setActiveBlockContextId ] =
+	useState< number | undefined >();

446-466: Remove ts-ignore and fix ID typing in preview rendering.

Once ProductContentWithProduct is typed and activeBlockContextId is numeric, we can drop the ignore and ensure proper comparisons.

-						// eslint-disable-next-line @typescript-eslint/ban-ts-comment
-						// @ts-ignore isLoading and product props are missing as they're coming from untyped withProduct HOC.
-						<ProductContentComponent
+						<ProductContentComponent
 							key={ blockContext.postId }
 							attributes={ {
 								productId: blockContext.postId,
 							} }
 							blocks={ blocks }
 							displayTemplate={ displayTemplate }
 							blockContext={ blockContext }
 							setActiveBlockContextId={ setActiveBlockContextId }
 						/>

Also ensure the display toggle compares numbers:

-const displayTemplate =
-	blockContext.postId === ( activeBlockContextId || blockContexts[ 0 ]?.postId );
+const displayTemplate =
+	blockContext.postId === ( activeBlockContextId ?? blockContexts?.[ 0 ]?.postId );
🧹 Nitpick comments (3)
plugins/woocommerce/client/blocks/assets/js/atomic/blocks/product-elements/price/edit.tsx (1)

93-113: Pass isDescendentOfSingleProductTemplate directly to Block.

Relying on the async setAttributes update can cause a transient mismatch on first render. Pass the computed value explicitly in both branches.

-					isExperimentalWcRestApiEnabled ? (
+					isExperimentalWcRestApiEnabled ? (
 						<Block
 							{ ...blockAttrs }
+							isDescendentOfSingleProductTemplate={
+								isDescendentOfSingleProductTemplate
+							}
 							isAdmin={ true }
 							product={ product }
 							isExperimentalWcRestApiV4Enabled={
 								isExperimentalWcRestApiEnabled
 							}
 						/>
 					) : (
 						<Block
 							{ ...blockAttrs }
+							isDescendentOfSingleProductTemplate={
+								isDescendentOfSingleProductTemplate
+							}
 							product={ undefined }
 							isAdmin={ false }
 							isExperimentalWcRestApiV4Enabled={ false }
 						/>
 					)
plugins/woocommerce/client/blocks/assets/js/shared/hocs/with-product-data-context.js (1)

36-36: Normalize id before fetching to keep hook input stable.

Prevents passing undefined/NaN to useStoreProducts.

-const id = getProductId( isDescendentOfQueryLoop, productId, postId );
+const id = Number( getProductId( isDescendentOfQueryLoop, productId, postId ) ) || 0;
plugins/woocommerce/client/blocks/assets/js/blocks/product-template/edit.tsx (1)

70-83: Accessibility/compat: replace deprecated onKeyPress.

Use onKeyDown and react to Enter/Space to keep the element keyboard-activable.

-			onKeyPress={ handleOnClick }
+			onKeyDown={ ( e ) => {
+				if ( e.key === 'Enter' || e.key === ' ' ) {
+					handleOnClick();
+				}
+			} }
📜 Review details

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3e6dd4b and 3d40baf.

📒 Files selected for processing (4)
  • plugins/woocommerce/changelog/fix-52960-limit-excessive-product-requests (1 hunks)
  • plugins/woocommerce/client/blocks/assets/js/atomic/blocks/product-elements/price/edit.tsx (2 hunks)
  • plugins/woocommerce/client/blocks/assets/js/blocks/product-template/edit.tsx (5 hunks)
  • plugins/woocommerce/client/blocks/assets/js/shared/hocs/with-product-data-context.js (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{php,js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/code-quality.mdc)

**/*.{php,js,jsx,ts,tsx}: Guard against unexpected inputs
Sanitize and validate any potentially dangerous inputs
Ensure code is backwards compatible
Write code that is readable and intuitive
Ensure code has unit or E2E tests where applicable

Files:

  • plugins/woocommerce/client/blocks/assets/js/shared/hocs/with-product-data-context.js
  • plugins/woocommerce/client/blocks/assets/js/atomic/blocks/product-elements/price/edit.tsx
  • plugins/woocommerce/client/blocks/assets/js/blocks/product-template/edit.tsx
**/*.{php,js,ts,jsx,tsx}

⚙️ CodeRabbit configuration file

**/*.{php,js,ts,jsx,tsx}: Don't trust that extension developers will follow the best practices, make sure the code:

  • Guards against unexpected inputs.
  • Sanitizes and validates any potentially dangerous inputs.
  • Is backwards compatible.
  • Is readable and intuitive.
  • Has unit or E2E tests where applicable.

Files:

  • plugins/woocommerce/client/blocks/assets/js/shared/hocs/with-product-data-context.js
  • plugins/woocommerce/client/blocks/assets/js/atomic/blocks/product-elements/price/edit.tsx
  • plugins/woocommerce/client/blocks/assets/js/blocks/product-template/edit.tsx
🧠 Learnings (3)
📚 Learning: 2025-06-23T05:47:52.696Z
Learnt from: samueljseay
PR: woocommerce/woocommerce#59051
File: plugins/woocommerce/client/blocks/assets/js/blocks/mini-cart/mini-cart-contents/inner-blocks/mini-cart-footer-block/index.tsx:66-70
Timestamp: 2025-06-23T05:47:52.696Z
Learning: For WooCommerce mini-cart blocks in plugins/woocommerce/client/blocks/assets/js/blocks/mini-cart/, the standardized conditional pattern for experimental features should be `if ( isExperimentalMiniCartEnabled() ) { blockSettings.save = () => <InnerBlocks.Content />; }` - defaulting to the traditional Save component and only overriding when the experimental feature is enabled.

Applied to files:

  • plugins/woocommerce/client/blocks/assets/js/atomic/blocks/product-elements/price/edit.tsx
📚 Learning: 2025-06-13T13:37:35.793Z
Learnt from: ralucaStan
PR: woocommerce/woocommerce#58782
File: plugins/woocommerce/client/blocks/assets/js/blocks/checkout/inner-blocks/checkout-shipping-address-block/customer-address.tsx:76-90
Timestamp: 2025-06-13T13:37:35.793Z
Learning: In plugins/woocommerce/client/blocks/assets/js/blocks/checkout/inner-blocks/checkout-shipping-address-block/customer-address.tsx, the `shouldAnimate` flag is expected to be `false` only on initial render and may remain `true` after the first edit; it does not need to be reset.

Applied to files:

  • plugins/woocommerce/client/blocks/assets/js/atomic/blocks/product-elements/price/edit.tsx
📚 Learning: 2025-07-24T05:37:00.907Z
Learnt from: dinhtungdu
PR: woocommerce/woocommerce#59900
File: plugins/woocommerce/client/blocks/assets/js/blocks/product-filters/inner-blocks/attribute-filter/inspector.tsx:0-0
Timestamp: 2025-07-24T05:37:00.907Z
Learning: The DisplayStyleSwitcher component in plugins/woocommerce/client/blocks/assets/js/blocks/product-filters/components/display-style-switcher/index.tsx has been updated so that its onChange prop accepts only a string type (not string | number | undefined), eliminating the need for type assertions when using this component.

Applied to files:

  • plugins/woocommerce/client/blocks/assets/js/atomic/blocks/product-elements/price/edit.tsx
  • plugins/woocommerce/client/blocks/assets/js/blocks/product-template/edit.tsx
🧬 Code graph analysis (2)
plugins/woocommerce/client/blocks/assets/js/atomic/blocks/product-elements/price/edit.tsx (2)
plugins/woocommerce/client/blocks/assets/js/settings/blocks/feature-flags.ts (1)
  • isExperimentalWcRestApiV4Enabled (25-31)
plugins/woocommerce/client/blocks/assets/js/atomic/blocks/product-elements/price/block.tsx (1)
  • Block (68-208)
plugins/woocommerce/client/blocks/assets/js/blocks/product-template/edit.tsx (1)
plugins/woocommerce/client/blocks/assets/js/types/type-defs/product-response.ts (1)
  • ProductResponseItem (59-103)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: build
  • GitHub Check: Check Asset Sizes
🔇 Additional comments (4)
plugins/woocommerce/client/blocks/assets/js/atomic/blocks/product-elements/price/edit.tsx (1)

78-79: Good: single evaluation of the feature flag.

Caching the flag avoids repeated getSetting calls and keeps render cheap.

plugins/woocommerce/client/blocks/assets/js/blocks/product-template/edit.tsx (3)

100-121: LGTM on splitting a lean ProductContent.

Cuts unnecessary product data wiring for collection previews. Good for perf.


258-266: LGTM: deriving isInSingleProductBlock via parents.

Efficient and avoids extra context wiring in collections.


361-364: LGTM: conditional selection of ProductContent variant.

This keeps withProduct only where necessary.

Comment on lines +78 to 81
const isExperimentalWcRestApiEnabled = isExperimentalWcRestApiV4Enabled();

const { product } = useProduct( context.postId );

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Guard useProduct with a numeric postId and avoid conditional hooks.

context.postId may be undefined or a string. Normalize to a number and always call the hook with a safe value.

-const isExperimentalWcRestApiEnabled = isExperimentalWcRestApiV4Enabled();
-
-const { product } = useProduct( context.postId );
+const isExperimentalWcRestApiEnabled = isExperimentalWcRestApiV4Enabled();
+const postId =
+	Number.isFinite( Number( context.postId ) ) ? Number( context.postId ) : undefined;
+const { product } = useProduct( postId as number | undefined );
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const isExperimentalWcRestApiEnabled = isExperimentalWcRestApiV4Enabled();
const { product } = useProduct( context.postId );
const isExperimentalWcRestApiEnabled = isExperimentalWcRestApiV4Enabled();
const postId =
Number.isFinite( Number( context.postId ) ) ? Number( context.postId ) : undefined;
const { product } = useProduct( postId as number | undefined );
🤖 Prompt for AI Agents
In
plugins/woocommerce/client/blocks/assets/js/atomic/blocks/product-elements/price/edit.tsx
around lines 78 to 81, the call to useProduct is passed context.postId which can
be undefined or a string; you must always call hooks unconditionally with a
numeric id. Normalize context.postId to a safe number before calling the hook
(e.g. const postId = Number(context.postId) || 0) and then call
useProduct(postId) so the hook always receives a numeric value and you avoid
conditional hook usage.

Comment on lines 10 to 11
const getProductById = ( products, id ) =>
products.find( ( product ) => product.id === id );

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Ensure strict equality matches by normalizing types.

If id is a string, product.id === id fails. Normalize to number.

-const getProductById = ( products, id ) =>
-	products.find( ( product ) => product.id === id );
+const getProductById = ( products, id ) => {
+	const nId = Number( id );
+	return products.find( ( product ) => product.id === nId );
+};
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const getProductById = ( products, id ) =>
products.find( ( product ) => product.id === id );
const getProductById = ( products, id ) => {
const nId = Number( id );
return products.find( ( product ) => product.id === nId );
};
🤖 Prompt for AI Agents
In
plugins/woocommerce/client/blocks/assets/js/shared/hocs/with-product-data-context.js
around lines 10 to 11, the product lookup uses strict equality without
normalizing types so string ids will not match numeric product.id; update the
function to normalize types before comparing (e.g., coerce the incoming id to a
Number or coerce product.id to string) and then use === for comparison to ensure
correct matches while avoiding loose equality.

Comment on lines +13 to +21
const getProductId = ( isDescendentOfQueryLoop, productId, postId ) => {
// Keep for backwards compatibility of Products (Beta) block.
if ( isDescendentOfQueryLoop ) {
return postId;
}

return productId || postId;
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Coerce IDs to numbers to avoid mismatches and missed lookups.

postId/productId can be strings (e.g., from block context). Ensure getProductId returns a finite number.

-const getProductId = ( isDescendentOfQueryLoop, productId, postId ) => {
+const toInt = ( val ) => {
+	const n = Number( val );
+	return Number.isFinite( n ) ? n : 0;
+};
+const getProductId = ( isDescendentOfQueryLoop, productId, postId ) => {
 	// Keep for backwards compatibility of Products (Beta) block.
 	if ( isDescendentOfQueryLoop ) {
-		return postId;
+		return toInt( postId );
 	}
 
-	return productId || postId;
+	return toInt( productId || postId );
 };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const getProductId = ( isDescendentOfQueryLoop, productId, postId ) => {
// Keep for backwards compatibility of Products (Beta) block.
if ( isDescendentOfQueryLoop ) {
return postId;
}
return productId || postId;
};
const toInt = ( val ) => {
const n = Number( val );
return Number.isFinite( n ) ? n : 0;
};
const getProductId = ( isDescendentOfQueryLoop, productId, postId ) => {
// Keep for backwards compatibility of Products (Beta) block.
if ( isDescendentOfQueryLoop ) {
return toInt( postId );
}
return toInt( productId || postId );
};
🤖 Prompt for AI Agents
In
plugins/woocommerce/client/blocks/assets/js/shared/hocs/with-product-data-context.js
around lines 13 to 21, getProductId may return string IDs which causes lookup
mismatches; coerce postId and productId to numbers and ensure they are finite
before returning. Specifically, when isDescendentOfQueryLoop is true, convert
postId to a Number and return it only if Number.isFinite; otherwise return
undefined/null; when not in a query loop, convert both productId and postId to
Numbers, prefer the finite productId, fall back to a finite postId, and return
undefined/null if neither is a finite number. Ensure no other behavior changes.

{
// If experimental WC API is not available we must fallback to "old" way of fetching product data.
// Once it's available everywhere we can remove this fallback.
isExperimentalWcRestApiEnabled ? (

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you explain why we need this? The Block component of the price block already handles the REST API v4 checking.

@kmanijak kmanijak Sep 12, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, it does but that creates a gap.

If we pass product from edit.tsx then it's used as a context for Block in block.tsx but then if isExperimentalWcRestApiEnabled is not enabled then the whole mapping here doesn't happen which results in... no data. We kind of tell the provider there's a product data and bail last minute just before rendering.

It worked before this PR only because of withProduct which provided product data no matter what. After getting rid of it, we need to rely on withProductDataContext mechanism that either:

  • uses product if provided (this is the case when isExperimentalWcRestApiEnabled is true)
  • fetches product otherwise.

This is to avoid situation when we provide product that's not enough to display data in editor.

Does it make sense? 😅

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is to avoid situation when we provide product that's not enough to display data in editor.

Can you provide a specific example? I tested the price display in the Product, All Products, and Products Beta blocks, and it shows correctly in all cases.

In the Block component of the price block, we only use the passed product context in the following location:

const { product } = useProductDataContext(
/**
* This block can depend on the core-data package only when the experimental WC Rest API feature flag is enabled because
* it depends on experimental fields: https://github.com/woocommerce/woocommerce/pull/60101
*/
isExperimentalWcRestApiV4Enabled
? {
isAdmin,
product: productData,
}
: undefined
);

If the experimental REST API is not available, it passes undefined to useProductDataContext. Checking for REST API v4 in the Edit component does not seem to make a difference.

@kmanijak kmanijak Sep 12, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here's the demo with this condition reverted: #60889 (branch name: try/revert-price-edit-demo). When you insert Product Collection there is no price displayed.

image

I made a mistake in previous explanation trying to base on memory, apologies. So here's how the broken flow goes (if we removed this condition):

  1. In edit.tsx we pass product from useProduct
  2. Then block.tsx exports Block wrapped with withProductDataContext
    3.Here

https://github.com/woocommerce/woocommerce/blob/59549aa46d8078a011992d3dd895b2dbdb991916/plugins/woocommerce/client/blocks/assets/js/shared/hocs/with-product-data-context.js#L59C10-L81C3

because inAdmin is true and we have a product OriginalComponent is returned without going through OriginalComponentWithContext which actually renders a context provider.
4. So then, when we go into block.tsx and make a decision to fallback to product provider in the place you showed:

const { product } = useProductDataContext(
/**
* This block can depend on the core-data package only when the experimental WC Rest API feature flag is enabled because
* it depends on experimental fields: https://github.com/woocommerce/woocommerce/pull/60101
*/
isExperimentalWcRestApiV4Enabled
? {
isAdmin,
product: productData,
}
: undefined
);

it returns the default product (id: 0, price: 0 etc.) because there's no provider.

Does that explain it better? We can sync if that would be helpful 😄

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So we need this condition to make sure block is wrapped with ProductDataContextProvider in here

https://github.com/woocommerce/woocommerce/blob/9486bba9a1e65f0d44dac90685e50b6110c47c31/plugins/woocommerce/client/blocks/assets/js/shared/hocs/with-product-data-context.js#L43C8-L51C3

otherwise we can't fallback in block.tsx since it's too late.

@dinhtungdu dinhtungdu left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for the explanation. It looks good to me now!

@kmanijak
kmanijak merged commit 5889e17 into trunk Sep 15, 2025
@kmanijak
kmanijak deleted the fix/52960-limit-excessive-product-requests branch September 15, 2025 07:29
@github-actions github-actions Bot added this to the 10.3.0 milestone Sep 15, 2025
@coderabbitai coderabbitai Bot mentioned this pull request Oct 6, 2025
3 of 12 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

plugin: woocommerce Issues related to the WooCommerce Core plugin.

Projects

None yet

2 participants