Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: update default query of error page #4634

Closed
wants to merge 4 commits into from
Closed

Conversation

tuin77
Copy link

@tuin77 tuin77 commented Oct 14, 2024

Description

fixed #4617
组件:vxe-table封装
问题:添加筛选条件并点击翻页,会导致页面查询结果可能不正确(页面返回了第一页,但没有数据)
解决:根据查询返回的总数量判断当前页码是否正确,不正确则重新请求
问题复现:先把筛选条件清空查询,复制从第一页列表已有的值输入Category输入框中,点击页码3查询结果不应该为空;

Type of change

Please delete options that are not relevant.

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update
  • Please, don't make changes to pnpm-lock.yaml unless you introduce a new test example.

Checklist

ℹ️ Check all checkboxes - this will indicate that you have done everything in accordance with the rules in CONTRIBUTING.

  • If you introduce new functionality, document it. You can run documentation with pnpm run docs:dev command.
  • Run the tests with pnpm test.
  • Changes in changelog are generated from PR name. Please, make sure that it explains your changes in an understandable manner. Please, prefix changeset messages with feat:, fix:, perf:, docs:, or chore:.
  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes
  • Any dependent changes have been merged and published in downstream modules

Summary by CodeRabbit

  • New Features

    • Introduced a filtering capability for mock data, allowing users to retrieve specific subsets based on defined criteria.
  • Improvements

    • Enhanced pagination handling to ensure the current page adjusts correctly when the total number of items changes, improving user experience during data navigation.

@tuin77 tuin77 requested review from anncwb, vince292007 and a team as code owners October 14, 2024 07:39
Copy link

changeset-bot bot commented Oct 14, 2024

⚠️ No Changeset found

Latest commit: e603473

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link
Contributor

coderabbitai bot commented Oct 14, 2024

Walkthrough

This pull request introduces a new function, filterMockData, to filter mock data based on specified criteria. The function processes an array of items and an object of filters, returning a filtered list. Additionally, the event handler is updated to integrate this filtering functionality. In another part of the code, the extendProxyOption function is modified to adjust the current page when the total items returned are less than the selected page, enhancing pagination handling.

Changes

File Path Change Summary
apps/backend-mock/api/table/list.ts Added function filterMockData(items = [], filters = {}) to filter mock data based on criteria. Modified event handler to use this function.
packages/effects/plugins/src/vxe-table/extends.ts Modified extendProxyOption to adjust currentPage when total items are less than the selected page.

Assessment against linked issues

Objective Addressed Explanation
Adjust pagination handling to prevent empty queries when filters are modified (#4617)

Possibly related PRs

Suggested labels

bug

Suggested reviewers

  • vince292007
  • anncwb

Poem

In the meadow where data flows,
A rabbit hops where the filter grows.
With pages turning, we adjust the view,
Finding treasures in the data anew! 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 5

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between ea962e7 and 60a63fe.

📒 Files selected for processing (2)
  • apps/backend-mock/api/table/list.ts (2 hunks)
  • packages/effects/plugins/src/vxe-table/extends.ts (1 hunks)
🧰 Additional context used
🔇 Additional comments (1)
apps/backend-mock/api/table/list.ts (1)

62-66: Integration of filterMockData function looks good.

The event handler correctly captures query parameters and applies the filtering function to the mock data.

@@ -38,6 +38,18 @@ function extendProxyOption(
const wrapperFn = async (params: any, _formValues: any, ...args: any[]) => {
const formValues = getFormValues();
const data = await configFn(params, formValues, ...args);

// 假如数据变少,导致总页数变少并小于当前选中页码,通过getPaginationRef获取到的页码是不正确的,需获取正确的页码再次执行
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Translate comments to English for consistency

The comment on line 42 is in Chinese. For consistency and maintainability, please translate comments to English so that all contributors can understand the code.

@@ -38,6 +38,18 @@ function extendProxyOption(
const wrapperFn = async (params: any, _formValues: any, ...args: any[]) => {
const formValues = getFormValues();
const data = await configFn(params, formValues, ...args);

// 假如数据变少,导致总页数变少并小于当前选中页码,通过getPaginationRef获取到的页码是不正确的,需获取正确的页码再次执行
const { total } = proxyConfig?.response as any;
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Avoid using as any; define proper typings for proxyConfig.response

Using as any bypasses type checking and may introduce unexpected errors. Consider defining proper types or interfaces for proxyConfig.response to ensure type safety and improve maintainability.

Comment on lines 47 to 49
const currentTotalPage = Math.ceil(resultTotal / pageSize);
if (currentPage > currentTotalPage) {
params.page.currentPage = currentTotalPage;
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Handle the case when currentTotalPage is zero to prevent invalid currentPage

When resultTotal is zero, currentTotalPage becomes zero due to Math.ceil(0 / pageSize). Pagination typically starts from page 1, so setting currentPage to zero may cause issues. Consider ensuring that currentTotalPage is at least 1 to avoid setting an invalid currentPage.

Apply this diff to adjust the calculation:

-      const currentTotalPage = Math.ceil(resultTotal / pageSize);
+      const currentTotalPage = Math.max(1, Math.ceil(resultTotal / pageSize));
📝 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 currentTotalPage = Math.ceil(resultTotal / pageSize);
if (currentPage > currentTotalPage) {
params.page.currentPage = currentTotalPage;
const currentTotalPage = Math.max(1, Math.ceil(resultTotal / pageSize));
if (currentPage > currentTotalPage) {
params.page.currentPage = currentTotalPage;

@@ -35,6 +35,22 @@ function generateMockDataList(count: number) {

const mockData = generateMockDataList(100);

function filterMockData(items = [], filters = {}) {
if (!Object.keys(filters)) return items;
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix the condition to check if the filters object is empty.

The condition if (!Object.keys(filters)) will always evaluate to false because Object.keys(filters) returns an array, which is truthy even when empty. To properly check if the filters object is empty, you should check the length of the keys array.

Apply this diff to fix the condition:

-if (!Object.keys(filters)) return items;
+if (Object.keys(filters).length === 0) return items;
📝 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
if (!Object.keys(filters)) return items;
if (Object.keys(filters).length === 0) return items;

apps/backend-mock/api/table/list.ts Outdated Show resolved Hide resolved
@anncwb
Copy link
Collaborator

anncwb commented Oct 14, 2024

ai有些建议。
然后我的想法是,输入框的参数,在没点击查询之前,应该是不能被应用的,所以可能点击跳转页数,不需要携带这个新的参数,应该是需要旧的参数。这样分页应该也不会有问题。

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (3)
packages/effects/plugins/src/vxe-table/extends.ts (1)

41-52: Excellent implementation to address pagination issues

The added logic effectively solves the problem described in the PR objectives. It correctly handles cases where the total number of items is less than the current selected page, ensuring that users always see valid data.

Some notable improvements:

  1. The use of Math.max(1, Math.ceil(resultTotal / pageSize)) prevents issues with zero pages.
  2. The recursive call to wrapperFn ensures that the correct data is fetched after adjusting the page number.

For improved readability, consider extracting the page calculation logic into a separate function:

function calculateCurrentPage(resultTotal: number, pageSize: number, currentPage: number): number {
  const currentTotalPage = Math.max(1, Math.ceil(resultTotal / pageSize));
  return Math.min(currentPage, currentTotalPage);
}

// Then in the main function:
if (Number(resultTotal)) {
  const newCurrentPage = calculateCurrentPage(resultTotal, pageSize, currentPage);
  if (newCurrentPage !== currentPage) {
    params.page.currentPage = newCurrentPage;
    return await wrapperFn(params, _formValues, ...args);
  }
}

This refactoring would make the logic more modular and easier to test.

apps/backend-mock/api/table/list.ts (2)

66-70: Consider separating filter application from pagination.

The current implementation applies filters on every page change, which aligns with the PR objectives of fixing the empty result issue. However, it doesn't fully address the concern raised in the comments about applying filters only when the search button is clicked.

To better align with the suggested behavior:

  1. Consider storing the last applied filters separately from the current input values.
  2. Only update these stored filters when the search button is clicked.
  3. Use the stored filters for pagination, rather than the current query parameters.

This approach would prevent unexpected filter applications during pagination and ensure that the user's navigation experience matches their expectations.

Would you like assistance in implementing this separation of concerns?


Line range hint 38-70: Summary: Good progress, but further refinement needed

The changes in this PR make significant progress towards addressing the issue of empty results when filtering and paginating. The filterMockData function is well-implemented and provides robust filtering capabilities.

However, to fully align with the PR objectives and the suggestions in the comments:

  1. Consider implementing a state management solution to store the last applied filters separately from the current input values.
  2. Modify the event handler to only apply new filters when a "search" or "apply filters" action is triggered.
  3. Use the stored (last applied) filters for pagination operations.

These additional changes would ensure that the pagination behavior matches user expectations and prevents unexpected filter applications during navigation.

Would you like assistance in outlining a more comprehensive solution that addresses these points?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 60a63fe and 360dd4c.

📒 Files selected for processing (2)
  • apps/backend-mock/api/table/list.ts (2 hunks)
  • packages/effects/plugins/src/vxe-table/extends.ts (1 hunks)
🧰 Additional context used
🔇 Additional comments (2)
packages/effects/plugins/src/vxe-table/extends.ts (1)

Line range hint 1-85: Summary of the review

The changes implemented in this file effectively address the pagination issues described in the PR objectives. The new logic handles cases where the total number of items is less than the current selected page, ensuring that users always see valid data.

Key points:

  1. The implementation aligns with the suggested approach in the PR comments.
  2. Previous concerns about handling zero pages and translating comments have been addressed.
  3. Minor suggestions for improvements have been provided, including:
    • Extracting the page calculation logic into a separate function for better readability and testability.
    • Improving type safety by defining proper types for proxyConfig.response.

Overall, the changes are well-implemented and solve the reported issue. Addressing the minor suggestions would further enhance the code quality.

apps/backend-mock/api/table/list.ts (1)

38-56: LGTM! Implementation addresses previous concerns.

The filterMockData function looks well-implemented. It correctly handles the filtering of mock data based on the provided criteria. The function addresses the previous concerns:

  1. The empty object check now uses Object.keys(filters).length === 0, which is the correct way to check for an empty object.
  2. Falsy values are properly handled by removing null, undefined, and empty string values from the filters object before processing.

The filtering logic is robust, handling both direct value comparisons and array inclusions. This implementation should work well with the vxe-table component mentioned in the PR objectives.

packages/effects/plugins/src/vxe-table/extends.ts Outdated Show resolved Hide resolved
@tuin77
Copy link
Author

tuin77 commented Oct 15, 2024

沿用v2版本的逻辑,感觉也更符合用户的预期,用户输入筛选值点击翻页自然是想查询,俺家产品倾向这种结果😄

// If the page is incorrect, make corrections and request again
const total = proxyConfig?.response?.total as string;
const { pageSize, currentPage } = params.page;
const resultTotal: number = data[total];
Copy link
Collaborator

@anncwb anncwb Oct 16, 2024

Choose a reason for hiding this comment

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

这里会有问题,total会有嵌套,比如 result.total, 这个时候这个写法有问题

Copy link
Author

Choose a reason for hiding this comment

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

已添加对嵌套result.total类型支持

@ZhangXY-Magic
Copy link

沿用v2版本的逻辑,感觉也更符合用户的预期,用户输入筛选值点击翻页自然是想查询,俺家产品倾向这种结果😄

我提这个问题也是倾向于未点击查询,筛选参数不应生效,我看了下antd的protable也是这种逻辑

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (1)
packages/effects/plugins/src/vxe-table/extends.ts (1)

46-56: LGTM: Improved pagination handling

The new pagination logic effectively handles cases where the current page might become invalid due to changes in the total number of items. The recursive approach to refetch data with the corrected page number is elegant.

For improved clarity, consider adding a comment explaining the recursive call:

if (currentPage > currentTotalPage) {
  params.page.currentPage = currentTotalPage;
  // Refetch data with the corrected page number
  return await wrapperFn(params, _formValues, ...args);
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 360dd4c and e603473.

📒 Files selected for processing (1)
  • packages/effects/plugins/src/vxe-table/extends.ts (2 hunks)
🧰 Additional context used
🔇 Additional comments (4)
packages/effects/plugins/src/vxe-table/extends.ts (4)

5-5: LGTM: New utility functions imported

The addition of getNestedValue import is appropriate for the new logic implemented. The isFunction import consolidation improves code organization.


42-42: Translate comment to English for consistency

The comment on line 42 is in Chinese. For consistency and maintainability, please translate it to English so that all contributors can understand the code.


47-49: LGTM: Flexible total calculation addressing nested structures

The updated resultTotal calculation effectively handles various scenarios, including function-based totals and nested object structures. The use of getNestedValue addresses the concern raised in the previous comment about handling nested totals like result.total.

This implementation provides the flexibility needed to work with different API response structures.


41-56: Summary: Improved pagination handling aligns with PR objectives

The implemented changes effectively address the pagination issues mentioned in the PR objectives. By recalculating the current page based on the total number of results, the code now handles cases where filter conditions might lead to incorrect query results. This solution ensures that users will always see the correct data, even when the total number of items changes due to filtering.

Key improvements:

  1. Flexible total extraction from various response structures
  2. Proper handling of cases where the current page becomes invalid
  3. Automatic correction and refetching of data when necessary

These changes significantly enhance the robustness of the vxe-table component's pagination functionality.

Comment on lines +43 to +45
const response = proxyConfig?.response || {};
const total = response?.total;

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve type safety for response handling

The response handling logic looks good, but we can improve type safety. Consider defining a proper type for proxyConfig.response instead of using optional chaining.

Here's a suggestion to improve the typing:

interface ProxyConfigResponse {
  total?: string | number | ((params: { data: any; $grid: any }) => number);
}

const response = (proxyConfig?.response || {}) as ProxyConfigResponse;
const total = response.total;

This change will provide better type checking and autocompletion for the response object properties.

@tuin77
Copy link
Author

tuin77 commented Oct 17, 2024

沿用v2版本的逻辑,感觉也更符合用户的预期,用户输入筛选值点击翻页自然是想查询,俺家产品倾向这种结果😄

我提这个问题也是倾向于未点击查询,筛选参数不应生效,我看了下antd的protable也是这种逻辑

那不如两种都支持 做成配置项

@anncwb
Copy link
Collaborator

anncwb commented Oct 17, 2024

这个有时间我再看下,先放着

@anncwb
Copy link
Collaborator

anncwb commented Nov 9, 2024

还是决定选择保持未提交的表单,不应该被携带的原则,已在 #4847 修复。

@anncwb anncwb closed this Nov 9, 2024
@github-actions github-actions bot locked and limited conversation to collaborators Dec 15, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Bug: vxe表格搜索表单页面,点击分页,默认携带未生效表单参数导致查询异常
3 participants