Skip to content

fix(autocomplete): return value instead of label in form submission#3375

Closed
wingkwong wants to merge 33 commits into
beta/release-nextfrom
fix/eng-1067
Closed

fix(autocomplete): return value instead of label in form submission#3375
wingkwong wants to merge 33 commits into
beta/release-nextfrom
fix/eng-1067

Conversation

@wingkwong
Copy link
Copy Markdown
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.

@linear
Copy link
Copy Markdown

linear Bot commented Jun 30, 2024

@vercel
Copy link
Copy Markdown

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

@changeset-bot
Copy link
Copy Markdown

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

@coderabbitai
Copy link
Copy Markdown
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
Copy Markdown
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.

Comment thread packages/components/autocomplete/src/use-autocomplete.ts
Comment thread packages/components/autocomplete/src/use-autocomplete.ts
@ehsanrezaeee
Copy link
Copy Markdown

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
Copy Markdown

Thanks. really appreciate it 🙌👌

Comment thread .changeset/purple-pillows-beg.md Outdated
@ryo-manba
Copy link
Copy Markdown
Contributor

@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
Copy Markdown
Member Author

wingkwong commented Nov 18, 2024

let's have an internal discussion.

@ryo-manba
Copy link
Copy Markdown
Contributor

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