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(autocomplete): return value instead of label in form submission #3375

Closed
wants to merge 33 commits into from

Conversation

wingkwong
Copy link
Member

@wingkwong wingkwong commented Jun 30, 2024

📝 Description

Similar to Select, use a hidden input to hold the actual value.

⛳️ Current behavior (updates)

The value in Input is actually label. In form submission, users need the value instead of the label.

const animals = [
  {label: "Big Cat", value: "cat"},
  {label: "Big Dog", value: "dog"},
];

const handleSubmit = (e) => {
  e.preventDefault();
  const value = e.target.animal.value;

  console.log(value); // showing `Big Cat` while `cat` is expected
};

return (
  <form onSubmit={handleSubmit}>
    <Autocomplete
      defaultItems={animals}
      defaultSelectedKey="cat"
      label="Favorite Animal"
      name="animal"
    >
      {(item) => <AutocompleteItem key={item.value}>{item.label}</AutocompleteItem>}
    </Autocomplete>

    <Button type="submit">Submit</Button>
  </form>
);

🚀 New behavior

Please describe the behavior or changes this PR adds

💣 Is this a breaking change (Yes/No):

Yes. Existing form values will be different after this change.

📝 Additional Information

Summary by CodeRabbit

  • New Features

    • Enhanced form submission process for autocomplete, returning actual values instead of labels.
    • Introduced a new WithFormTemplate for submitting selected values, displaying alerts upon submission.
  • Bug Fixes

    • Improved handling of required fields and validation in the autocomplete component.
  • Tests

    • Expanded test coverage for the Autocomplete component, ensuring accurate form value retrieval and validation.
  • Documentation

    • Updated stories to include new templates demonstrating form integration with the autocomplete feature.

Copy link

linear bot commented Jun 30, 2024

Copy link

vercel bot commented Jun 30, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
nextui-docs-v2 ❌ Failed (Inspect) Nov 18, 2024 6:02am
nextui-storybook-v2 ❌ Failed (Inspect) Nov 18, 2024 6:02am

Copy link

changeset-bot bot commented Jun 30, 2024

🦋 Changeset detected

Latest commit: 09bcf2b

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 2 packages
Name Type
@nextui-org/autocomplete Patch
@nextui-org/react Patch

Not sure what this means? Click here to learn what changesets are.

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

Copy link
Contributor

coderabbitai bot commented Jun 30, 2024

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

🗂️ Base branches to auto review (5)
  • main
  • canary
  • fix/.*
  • chore/.*
  • feat/.*

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The changes in this pull request modify the behavior of the autocomplete component to return the actual value of the selected option instead of its label during form submission. This adjustment addresses issues #3353 and #3343. Additionally, the @react-aria/form dependency has been added to enhance form handling capabilities. The test suite for the autocomplete component has been updated to improve coverage and validation of form interactions. New functionality for managing hidden inputs has also been introduced, along with a new story template for demonstrating form submissions.

Changes

File Change Summary
.changeset/purple-pillows-beg.md Updated form submission to return actual value from autocomplete; added dependency on @react-aria/form.
packages/components/autocomplete/tests/autocomplete.test.tsx Enhanced tests for Autocomplete component; added validation for form handling and required fields.
packages/components/autocomplete/src/autocomplete.tsx Integrated HiddenInput component; modified Autocomplete to include hidden input properties.
packages/components/autocomplete/src/hidden-input.tsx Introduced HiddenInput component with hooks for managing hidden inputs in autocomplete context.
packages/components/autocomplete/src/use-autocomplete.ts Updated useAutocomplete hook to include onSelectionChange callback; improved input state management.
packages/components/autocomplete/stories/autocomplete.stories.tsx Added WithFormTemplate for demonstrating form submissions with autocomplete selections.

Assessment against linked issues

Objective Addressed Explanation
Return the actual value instead of the label on form submission (3353)
Capture the correct ID value instead of the label in dynamic data (3343)

Possibly related PRs

Suggested reviewers

  • jrgarciadev
  • ryo-manba

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.

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: 7

🧹 Outside diff range and nitpick comments (6)
.changeset/purple-pillows-beg.md (1)

1-5: LGTM! Minor suggestion for clarity.

The changeset correctly indicates a minor version bump for the autocomplete component, which is appropriate for this functional change. The description accurately summarizes the modification and references the relevant issues.

Consider slightly expanding the change description for added clarity:

-return autocomplete value instead of label in form submission (#3353, #3343)
+fix(autocomplete): return selected value instead of label in form submission (#3353, #3343)

This minor adjustment adds context about the component being modified and clarifies that it's the selected value being returned.

packages/components/autocomplete/package.json (1)

58-58: Approved: Addition of @react-aria/form dependency

The addition of the "@react-aria/form" dependency is appropriate for enhancing the form handling capabilities of the Autocomplete component. This change aligns well with the PR objectives to modify the component's behavior during form submissions.

Consider using a caret (^) version range instead of an exact version to allow for compatible updates:

-    "@react-aria/form": "3.0.5",
+    "@react-aria/form": "^3.0.5",

This change would allow for minor version updates that include bug fixes and non-breaking changes, potentially improving the package's maintenance in the long run.

packages/components/autocomplete/stories/autocomplete.stories.tsx (1)

767-787: LGTM! The implementation addresses the PR objectives.

The WithFormTemplate function correctly demonstrates how the Autocomplete component can be used within a form, addressing the issue of returning the value instead of the label during form submission. A few suggestions for improvement:

  1. Consider adding TypeScript types for the event parameter in the handleSubmit function.
  2. The alert and console.log are fine for demonstration purposes, but it might be worth adding a comment to indicate that these are for demo purposes only.

Here's a suggested improvement for the handleSubmit function:

- const handleSubmit = (e) => {
+ const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const name = e.target.animal.value;

-   // eslint-disable-next-line no-console
-   console.log(name);
-   alert("Submitted value: " + name);
+   // These logs are for demonstration purposes only
+   console.log("Submitted value:", name);
+   alert(`Submitted value: ${name}`);
  };
packages/components/autocomplete/src/hidden-input.tsx (2)

9-23: Unused label prop in AriaHiddenInputProps

The label prop is defined in AriaHiddenInputProps but is not used in the useHiddenInput hook or the HiddenInput component. This may cause confusion or indicate leftover code.

Consider removing the label prop if it's not necessary:

 export interface AriaHiddenInputProps {
   /**
    * Describes the type of autocomplete functionality the input should provide if any.
    * See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#htmlattrdefautocomplete).
    */
   autoComplete?: string;
-  /** The text label for the input. */
-  label?: ReactNode;
   /** HTML form input name. */
   name?: string;
   /** Sets the disabled state of the input. */
   isDisabled?: boolean;
   /** Whether the input is required. */
   isRequired?: boolean;
 }

Alternatively, if label is intended for future use, please ensure it's utilized appropriately.


41-85: Consider adding unit tests for useHiddenInput and HiddenInput

Adding unit tests for these components will help ensure their reliability and catch potential issues early.

Would you like assistance in setting up unit tests for these components or opening a GitHub issue to track this task?

packages/components/autocomplete/src/use-autocomplete.ts (1)

553-575: Optimize dependency array in useCallback hook

In the getHiddenInputProps function, some dependencies in the useCallback hook's dependency array may be unnecessary or could cause unnecessary re-creations of the function.

Review the dependencies and consider simplifying them:

useCallback(
  (props = {}) => ({
    state,
    inputRef,
    hiddenInputRef,
    name: originalProps?.name,
    isRequired: originalProps?.isRequired,
    autoComplete: originalProps?.autoComplete,
    isDisabled: originalProps?.isDisabled,
    onChange,
    ...props,
  }),
  [
    state,
    originalProps?.name,
    originalProps?.autoComplete,
    originalProps?.isDisabled,
    originalProps?.isRequired,
-   inputRef,
-   hiddenInputRef,
+   inputRef.current,
+   hiddenInputRef.current,
  ],
);

Alternatively, if inputRef and hiddenInputRef are stable (do not change across renders), they can be omitted from the dependency array.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 781b855 and f8cce31.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (7)
  • .changeset/purple-pillows-beg.md (1 hunks)
  • packages/components/autocomplete/tests/autocomplete.test.tsx (3 hunks)
  • packages/components/autocomplete/package.json (1 hunks)
  • packages/components/autocomplete/src/autocomplete.tsx (3 hunks)
  • packages/components/autocomplete/src/hidden-input.tsx (1 hunks)
  • packages/components/autocomplete/src/use-autocomplete.ts (9 hunks)
  • packages/components/autocomplete/stories/autocomplete.stories.tsx (2 hunks)
🧰 Additional context used
🪛 Biome
packages/components/autocomplete/src/use-autocomplete.ts

[error] 464-464: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

🔇 Additional comments (12)
packages/components/autocomplete/src/autocomplete.tsx (3)

12-12: LGTM: New import for HiddenInput

The import for HiddenInput is correctly placed and necessary for the new functionality being added to the Autocomplete component.


33-33: LGTM: Addition of getHiddenInputProps

The inclusion of getHiddenInputProps in the destructured return from useAutocomplete is consistent with the PR objectives and follows the existing naming conventions. This change enables the component to manage hidden input properties, which is crucial for returning the correct value during form submissions.


48-48: LGTM: Addition of HiddenInput component

The inclusion of the HiddenInput component effectively addresses the PR objectives by providing a mechanism to store and submit the actual value instead of the label. Its placement and usage of getHiddenInputProps are appropriate.

To ensure this change works as intended, please run the following verification script:

This script will help verify the correct implementation and usage of the HiddenInput component. Please review the results to ensure everything is in order.

packages/components/autocomplete/stories/autocomplete.stories.tsx (2)

1029-1035: LGTM! The export is correctly implemented.

The WithForm export is properly added, following the established pattern for other examples in this file. It correctly uses the WithFormTemplate render function and includes the defaultProps.


Line range hint 767-1035: Summary: The changes effectively address the PR objectives.

The addition of the WithFormTemplate and its corresponding export WithForm successfully demonstrates the correct usage of the Autocomplete component within a form. These changes address the issue where the Autocomplete component was returning the label instead of the value during form submission.

Key improvements:

  1. The Autocomplete component now uses a name prop, allowing it to be included in form data.
  2. The handleSubmit function correctly retrieves the value using e.target.animal.value.
  3. The AutocompleteItems use different keys and labels, effectively testing if the correct value (key) is submitted.

These changes will help users understand how to properly implement form submission with the Autocomplete component, resolving the issues mentioned in #3353 and #3343.

packages/components/autocomplete/src/hidden-input.tsx (6)

1-6: Approved: Import statements are appropriate

The import statements correctly bring in all required dependencies.


7-8: Approved: Importing inputData

The inputData is properly imported from "./use-autocomplete".


25-31: Approved: Combining input props correctly

The types NativeHTMLInputProps and CombinedAriaInputProps are correctly defined to merge native input attributes with custom props.


32-39: Approved: Definition of HiddenInputProps

The HiddenInputProps interface appropriately extends CombinedAriaInputProps and includes additional properties needed for the component.


73-77: Verify that onChange handler updates state correctly

In the onChange handler for the hidden input, state.setSelectedKey(e.target.value) updates the selected key in the state. Ensure that this correctly synchronizes with the visible input and that the onChange prop behaves as expected.


81-85: Approved: HiddenInput component implementation

The HiddenInput component correctly utilizes the useHiddenInput hook and renders an <input> element with the appropriate properties.

packages/components/autocomplete/__tests__/autocomplete.test.tsx (1)

867-888: Test case effectively verifies form value correctness

The newly added test case robustly checks that the form values are correctly captured after user interactions, ensuring the Autocomplete component integrates well with React Hook Form.

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: 2

🧹 Outside diff range and nitpick comments (2)
packages/components/autocomplete/src/use-autocomplete.ts (2)

118-125: LGTM: New InputData interface and inputData WeakMap added

The addition of the InputData interface and inputData WeakMap is a good approach for managing input-related data. The use of a WeakMap is efficient and allows for garbage collection of unused ComboBoxState instances.

However, it would be helpful to add a comment explaining the purpose of the inputData WeakMap for better code maintainability.

Consider adding a comment above the inputData declaration, like this:

// WeakMap to associate ComboBoxState instances with their corresponding InputData
// This allows for efficient storage and retrieval of input-related data
export const inputData = new WeakMap<ComboBoxState<any>, InputData>();

Line range hint 181-224: LGTM with suggestion: Implementation of onSelectionChange

The implementation of onSelectionChange in the useComboBoxState configuration is good. It correctly handles selection changes and updates the form value, addressing the main objective of returning the actual value instead of the label.

However, there's a potential issue when accessing hiddenInputRef.current.

Add a null check before accessing hiddenInputRef.current to prevent potential runtime errors:

onSelectionChange: (keys) => {
  onSelectionChange?.(keys);
  if (onChange && typeof onChange === "function") {
    onChange({
      target: {
        name: hiddenInputRef?.current?.name,
        value: keys,
      },
    } as React.ChangeEvent<HTMLInputElement>);
  }
},

Consider refactoring to:

onSelectionChange: (keys) => {
  onSelectionChange?.(keys);
  if (onChange && typeof onChange === "function") {
    const name = hiddenInputRef?.current?.name;
    onChange({
      target: {
        name,
        value: keys,
      },
    } as React.ChangeEvent<HTMLInputElement>);
  }
},
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between f8cce31 and 1a84b7b.

📒 Files selected for processing (1)
  • packages/components/autocomplete/src/use-autocomplete.ts (9 hunks)
🧰 Additional context used
🪛 Biome
packages/components/autocomplete/src/use-autocomplete.ts

[error] 464-464: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

🔇 Additional comments (3)
packages/components/autocomplete/src/use-autocomplete.ts (3)

113-117: LGTM: New onSelectionChange prop added

The addition of the onSelectionChange prop is a good improvement. It allows users to handle selection changes, which is crucial for the new functionality of returning the actual value instead of the label.


128-131: LGTM: Updated UseAutocompleteProps type

The update to the UseAutocompleteProps<T> type, excluding onSelectionChange from the Omit<InputProps, ...> part, is correct. This change ensures that the newly added onSelectionChange prop is properly typed and doesn't conflict with any similarly named prop from InputProps.


Line range hint 553-609: LGTM: Addition of getHiddenInputProps and related changes

The addition of the getHiddenInputProps function and the related changes are well-implemented:

  1. The getHiddenInputProps function is correctly memoized to optimize performance.
  2. The inputData WeakMap is properly populated with the necessary input-related data.
  3. The addition of getHiddenInputProps to the hook's return value allows consumers to easily apply the hidden input properties.

These changes effectively support the new functionality of using a hidden input to store the actual value, which is a key objective of this PR.

packages/components/autocomplete/src/use-autocomplete.ts Outdated Show resolved Hide resolved
packages/components/autocomplete/src/use-autocomplete.ts Outdated Show resolved Hide resolved
@ehsanrezaeee
Copy link

is there any progress on this issue? please merge so i can use the autocomplete component

@wingkwong wingkwong changed the base branch from canary to beta/release-next November 8, 2024 06:22
@ehsanrezaeee
Copy link

Thanks. really appreciate it 🙌👌

@ryo-manba
Copy link
Member

@wingkwong @jrgarciadev
I don't think this behavior is a bug.
Autocomplete works as an input, not a select. So, it makes sense to send the label (the displayed text) on form submission.

For example, if the key is a sent as the value, the Custom value feature will send the key instead of the user's input. This would not be useful.

@wingkwong
Copy link
Member Author

wingkwong commented Nov 18, 2024

let's have an internal discussion.

@ryo-manba
Copy link
Member

As mentioned in this comment, autocomplete is not a select, so the label is submitted.
If you want to submit a value other the label, please use a Select or handle it as a controlled component.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
4 participants