Skip to content

feat(PieChart): add dataKey to Legend payload#7137

Merged
PavelVanecek merged 1 commit into
recharts:mainfrom
Harikrushn9118:fix/pie-legend-datakey
Mar 25, 2026
Merged

feat(PieChart): add dataKey to Legend payload#7137
PavelVanecek merged 1 commit into
recharts:mainfrom
Harikrushn9118:fix/pie-legend-datakey

Conversation

@Harikrushn9118

@Harikrushn9118 Harikrushn9118 commented Mar 15, 2026

Copy link
Copy Markdown
Contributor

Fixes #7056. The Legend payload in PieChart lacked the dataKey property, unlike other charts such as AreaChart and LineChart. This PR adds the dataKey from Pie settings to the Pie legend payload for consistency across chart types.

Summary by CodeRabbit

  • Bug Fixes

    • Pie chart legend entries now include the chart's data key so legends reference the correct data field; this change is transparent to layouts and public APIs.
  • Tests

    • Added and updated tests to verify legend payloads include the chart's data key and that the data key matches the chart configuration, including when provided as a function.

@coderabbitai

coderabbitai Bot commented Mar 15, 2026

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

Adds a dataKey field to each Legend payload emitted for PieChart, sourcing the value from the corresponding Pie's dataKey (including function references). Tests updated to assert presence and correctness of dataKey.

Changes

Cohort / File(s) Summary
Pie Legend Selector
src/state/selectors/pieSelectors.ts
Augmented selectPieLegend output so each LegendPayload includes a dataKey populated from pieSettings.dataKey.
PieChart Tests
test/chart/PieChart.spec.tsx
Updated expected Legend payloads to include dataKey values; added assertions verifying dataKey matches the Pie's dataKey prop and that function dataKey references are preserved.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Suggested reviewers

  • PavelVanecek
  • ckifer
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description is incomplete; it lacks required sections like Motivation and Context, Testing details, and Types of changes checklist defined in the template. Add the missing template sections: Motivation and Context, How Has This Been Tested, Types of changes, and complete the Checklist with appropriate selections.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The PR title clearly and concisely describes the main change: adding dataKey to the Legend payload in PieChart.
Linked Issues check ✅ Passed The code changes successfully address all requirements from issue #7056: dataKey is added to Legend payload, enabling consumers to identify data fields and supporting multiple Pie elements.
Out of Scope Changes check ✅ Passed All changes are directly related to the linked issue #7056; the PR modifies only the Legend payload in PieChart and corresponding tests without introducing unrelated changes.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
📝 Coding Plan
  • Generate coding plan for human review comments

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.

🧹 Nitpick comments (1)
test/chart/PieChart.spec.tsx (1)

412-482: Add one multi-Pie legend selector test to lock in disambiguation behavior.

Given the PR goal, a case with two Pie components using different dataKey values would guard against regressions and verify that legend items can be mapped back to the correct Pie.

As per coding guidelines: test/**/*.{test,spec}.{ts,tsx}: "Aim for 100% unit test code coverage when writing new code".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/chart/PieChart.spec.tsx` around lines 412 - 482, Add a test that covers
the multi-Pie legend disambiguation by rendering a test case with two Pie
components that use different dataKey values, then invoke selectPieLegend for
one pie and assert the legend items map back to that Pie only; specifically,
update the PieChart.spec.tsx suite to add a new test (e.g., "selectPieLegend
with multiple pies") that uses renderTestCase to set up two pies, calls
selectPieLegend(state, 'pie1', undefined), and uses expectLastCalledWith to
verify the returned legend payloads correspond to the correct dataKey and
payloads for pie1; reference the existing selectPieLegend, renderTestCase, and
expectLastCalledWith helpers to implement the assertion.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@test/chart/PieChart.spec.tsx`:
- Around line 412-482: Add a test that covers the multi-Pie legend
disambiguation by rendering a test case with two Pie components that use
different dataKey values, then invoke selectPieLegend for one pie and assert the
legend items map back to that Pie only; specifically, update the
PieChart.spec.tsx suite to add a new test (e.g., "selectPieLegend with multiple
pies") that uses renderTestCase to set up two pies, calls selectPieLegend(state,
'pie1', undefined), and uses expectLastCalledWith to verify the returned legend
payloads correspond to the correct dataKey and payloads for pie1; reference the
existing selectPieLegend, renderTestCase, and expectLastCalledWith helpers to
implement the assertion.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 22916185-e853-4712-b4a0-a9fe1f3cc9cc

📥 Commits

Reviewing files that changed from the base of the PR and between 681daea and b8a0cb4.

📒 Files selected for processing (2)
  • src/state/selectors/pieSelectors.ts
  • test/chart/PieChart.spec.tsx

@codecov

codecov Bot commented Mar 15, 2026

Copy link
Copy Markdown

Bundle Report

Changes will increase total bundle size by 126 bytes (0.0%) ⬆️. This is within the configured threshold ✅

Detailed changes
Bundle name Size Change
recharts/bundle-cjs 1.29MB 36 bytes (0.0%) ⬆️
recharts/bundle-es6 1.12MB 36 bytes (0.0%) ⬆️
recharts/bundle-umd 545.82kB 18 bytes (0.0%) ⬆️
recharts/bundle-treeshaking-polar 443.11kB 36 bytes (0.01%) ⬆️

Affected Assets, Files, and Routes:

view changes for bundle: recharts/bundle-umd

Assets Changed:

Asset Name Size Change Total Size Change (%)
Recharts.js 18 bytes 545.82kB 0.0%
view changes for bundle: recharts/bundle-cjs

Assets Changed:

Asset Name Size Change Total Size Change (%)
state/selectors/pieSelectors.js 36 bytes 4.65kB 0.78%
view changes for bundle: recharts/bundle-es6

Assets Changed:

Asset Name Size Change Total Size Change (%)
state/selectors/pieSelectors.js 36 bytes 4.33kB 0.84%
view changes for bundle: recharts/bundle-treeshaking-polar

Assets Changed:

Asset Name Size Change Total Size Change (%)
bundle.js 36 bytes 443.11kB 0.01%

@hirotomoyamada hirotomoyamada left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Thanks!

@codecov

codecov Bot commented Mar 15, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 89.59%. Comparing base (681daea) to head (781d44b).
⚠️ Report is 21 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #7137   +/-   ##
=======================================
  Coverage   89.59%   89.59%           
=======================================
  Files         536      536           
  Lines       40401    40402    +1     
  Branches     5498     5498           
=======================================
+ Hits        36197    36198    +1     
  Misses       4196     4196           
  Partials        8        8           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@Harikrushn9118
Harikrushn9118 force-pushed the fix/pie-legend-datakey branch from 3ef11ce to 781d44b Compare March 15, 2026 10:20

@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.

🧹 Nitpick comments (1)
test/chart/PieChart.spec.tsx (1)

484-550: Good test coverage for the linked issue, with a minor suggestion.

The new test suite effectively validates:

  1. Legend payload contains dataKey
  2. The dataKey matches the Pie's prop value
  3. Function-typed dataKey is preserved by reference

Consider adding selector call count verification to align with coding guidelines for spotting unnecessary re-renders. For example:

expect(spy).toHaveBeenCalledTimes(3);

Additionally, the second test (lines 512-519) largely overlaps with the first test (lines 504-510), since both verify that dataKey equals 'visits'. Consider consolidating them if desired, though having explicit iteration is a valid stylistic choice for thoroughness.

Based on learnings: "Verify the number of selector calls using the spy object from createSelectorTestCase to spot unnecessary re-renders and improve performance"

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/chart/PieChart.spec.tsx` around lines 484 - 550, Add selector call count
assertions using the spy returned by createSelectorTestCase to detect
unnecessary re-renders: in the tests that call renderIssueTestCase and
renderFnTestCase (the tests using selectPieLegend for 'issue-pie' and 'fn-pie'),
add an assertion like expect(spy).toHaveBeenCalledTimes(3) (or the correct
expected number for the lifecycle of these selector calls) immediately after
obtaining spy to validate call count; ensure you reference the spy from
createSelectorTestCase and keep the existing payload/dataKey assertions intact.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@test/chart/PieChart.spec.tsx`:
- Around line 484-550: Add selector call count assertions using the spy returned
by createSelectorTestCase to detect unnecessary re-renders: in the tests that
call renderIssueTestCase and renderFnTestCase (the tests using selectPieLegend
for 'issue-pie' and 'fn-pie'), add an assertion like
expect(spy).toHaveBeenCalledTimes(3) (or the correct expected number for the
lifecycle of these selector calls) immediately after obtaining spy to validate
call count; ensure you reference the spy from createSelectorTestCase and keep
the existing payload/dataKey assertions intact.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 9171c430-446a-45a2-9c17-2f0f39bfdcb0

📥 Commits

Reviewing files that changed from the base of the PR and between fb5bb07 and 3ef11ce.

📒 Files selected for processing (1)
  • test/chart/PieChart.spec.tsx

@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.

🧹 Nitpick comments (2)
test/chart/PieChart.spec.tsx (2)

504-519: Consider consolidating redundant tests.

The test at lines 512-519 largely duplicates the verification in lines 504-510, as both confirm that dataKey equals 'visits'. Consider merging them into a single test or removing the redundant assertions.

Also, per coding guidelines, consider verifying the number of selector calls using expect(spy).toHaveBeenCalledTimes(...) to spot unnecessary re-renders.

♻️ Suggested consolidation
       test('Legend payload should contain dataKey', () => {
         const { spy } = renderIssueTestCase(state => selectPieLegend(state, 'issue-pie', undefined));
         expectLastCalledWith(spy, [
           expect.objectContaining({ dataKey: 'visits' }),
           expect.objectContaining({ dataKey: 'visits' }),
         ]);
+        expect(spy).toHaveBeenCalledTimes(3);
       });
 
-      test('Legend payload dataKey matches the Pie dataKey prop', () => {
-        const { spy } = renderIssueTestCase(state => selectPieLegend(state, 'issue-pie', undefined));
-        const payload = spy.mock.lastCall?.[0];
-        expect(payload).toBeDefined();
-        payload?.forEach(entry => {
-          expect(entry.dataKey).toBe('visits');
-        });
-      });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/chart/PieChart.spec.tsx` around lines 504 - 519, The two tests
duplicating verification of the Pie legend dataKey should be consolidated:
combine the assertions in the tests named "Legend payload should contain
dataKey" and "Legend payload dataKey matches the Pie dataKey prop" into a single
test that both checks the legend payload entries contain dataKey 'visits' (using
expect.objectContaining or iterating payload) and also asserts the selector was
invoked the expected number of times (use
expect(spy).toHaveBeenCalledTimes(...)); locate and update the tests that call
renderIssueTestCase and selectPieLegend (and the spy variable) to perform both
checks in one test and remove the redundant test.

521-549: Good coverage for function dataKey.

The test correctly verifies that when dataKey is a function, the function reference is preserved in the legend payload. Creating renderFnTestCase inside the test is acceptable here since it requires a different component configuration.

Minor suggestion: Add call count verification per coding guidelines.

♻️ Add call count verification
         const { spy } = renderFnTestCase(state => selectPieLegend(state, 'fn-pie', undefined));
         const payload = spy.mock.lastCall?.[0];
         expect(payload).toBeDefined();
         payload?.forEach(entry => {
           expect(entry.dataKey).toBe(dataKeyFn);
           expect(typeof entry.dataKey).toBe('function');
         });
+        expect(spy).toHaveBeenCalledTimes(3);
       });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/chart/PieChart.spec.tsx` around lines 521 - 549, Add a call-count
assertion for the test "Legend payload should contain dataKey even when dataKey
is a function": after creating renderFnTestCase and obtaining const { spy } =
renderFnTestCase(...) (the spy used with selectPieLegend/'fn-pie'), assert the
spy was invoked the expected number of times (e.g.,
expect(spy).toHaveBeenCalledTimes(1) or equivalent) before inspecting payload,
so the test verifies the selector was actually called once and follows
call-count guidelines.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@test/chart/PieChart.spec.tsx`:
- Around line 504-519: The two tests duplicating verification of the Pie legend
dataKey should be consolidated: combine the assertions in the tests named
"Legend payload should contain dataKey" and "Legend payload dataKey matches the
Pie dataKey prop" into a single test that both checks the legend payload entries
contain dataKey 'visits' (using expect.objectContaining or iterating payload)
and also asserts the selector was invoked the expected number of times (use
expect(spy).toHaveBeenCalledTimes(...)); locate and update the tests that call
renderIssueTestCase and selectPieLegend (and the spy variable) to perform both
checks in one test and remove the redundant test.
- Around line 521-549: Add a call-count assertion for the test "Legend payload
should contain dataKey even when dataKey is a function": after creating
renderFnTestCase and obtaining const { spy } = renderFnTestCase(...) (the spy
used with selectPieLegend/'fn-pie'), assert the spy was invoked the expected
number of times (e.g., expect(spy).toHaveBeenCalledTimes(1) or equivalent)
before inspecting payload, so the test verifies the selector was actually called
once and follows call-count guidelines.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 36090a69-345f-4ec8-b6ea-b9bb3f9af67e

📥 Commits

Reviewing files that changed from the base of the PR and between 3ef11ce and 781d44b.

📒 Files selected for processing (2)
  • src/state/selectors/pieSelectors.ts
  • test/chart/PieChart.spec.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/state/selectors/pieSelectors.ts

@PavelVanecek
PavelVanecek merged commit 8a5d9f2 into recharts:main Mar 25, 2026
52 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

The dataKey does not exist in the payload of the Legend within the PieChart.

4 participants