Skip to content

[TASK-14419] Improvement: Add debouncing to BIC field#1163

Closed
Zishan-7 wants to merge 1 commit intopeanut-wallet-devfrom
feat/bic-debouncing
Closed

[TASK-14419] Improvement: Add debouncing to BIC field#1163
Zishan-7 wants to merge 1 commit intopeanut-wallet-devfrom
feat/bic-debouncing

Conversation

@Zishan-7
Copy link
Contributor

@Zishan-7 Zishan-7 commented Sep 2, 2025

No description provided.

@notion-workspace
Copy link

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 2, 2025

Walkthrough

Implements debounced BIC validation in DynamicBankAccountForm by introducing a debounce hook, tracking validation state, gating API calls to debounced values, syncing debounced input back into the form, and updating submit button loading/disabled conditions accordingly.

Changes

Cohort / File(s) Summary
DynamicBankAccountForm debounced BIC validation
src/components/AddWithdraw/DynamicBankAccountForm.tsx
Integrates useDebounce for BIC, adds isCheckingBICValid state, watches BIC value, validates only on debounced value, updates form value with debounced BIC before validation, guards API calls, and adjusts submit button loading/disabled to include BIC-check state.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

enhancement

Suggested reviewers

  • kushagrasarathe
  • jjramirezn
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/bic-debouncing

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
🪧 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit 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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

@vercel
Copy link

vercel bot commented Sep 2, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
peanut-wallet Ready Ready Preview Comment Sep 2, 2025 10:04am

@coderabbitai coderabbitai bot added the enhancement New feature or request label Sep 2, 2025
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

🧹 Nitpick comments (3)
src/components/AddWithdraw/DynamicBankAccountForm.tsx (3)

71-71: Nit: fix setter casing for consistency.

Rename setisCheckingBICValidsetIsCheckingBICValid.

Apply locally within this line, and update its usages below to match.


101-104: Extract debounce delay to a named constant.

Improves readability and makes UX tuning easier.

-const debouncedBicValue = useDebounce(bicValue, 500) // 500ms delay
+const BIC_DEBOUNCE_MS = 500
+const debouncedBicValue = useDebounce(bicValue, BIC_DEBOUNCE_MS)

116-123: Avoid unnecessary setValue; trigger validation instead.

Calling setValue with the same value can cause extra renders and affect dirty state. Prefer triggering validation when the debounced value matches the current value; only set when it actually differs.

-useEffect(() => {
-    if (showBicField && debouncedBicValue && debouncedBicValue.trim().length > 0) {
-        // Trigger validation for the BIC field
-        setValue('bic', debouncedBicValue, { shouldValidate: true })
-    }
-}, [debouncedBicValue, showBicField, setValue])
+useEffect(() => {
+    if (!showBicField) return
+    const dv = debouncedBicValue?.trim()
+    if (!dv) return
+    const current = getValues('bic')?.trim()
+    if (current === dv) {
+        // value is stable; just trigger validation
+        trigger('bic')
+    } else {
+        // value changed; update and validate
+        setValue('bic', debouncedBicValue, { shouldValidate: true })
+    }
+}, [debouncedBicValue, showBicField, setValue, getValues, trigger])

Additional change (outside this range) to enable the above:

// add to useForm destructure
const { control, handleSubmit, setValue, getValues, watch, trigger, formState: { ... } } = useForm<IBankAccountDetails>({...})
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 24eb5b3 and 367bff2.

📒 Files selected for processing (1)
  • src/components/AddWithdraw/DynamicBankAccountForm.tsx (7 hunks)
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2024-10-25T11:33:46.776Z
Learnt from: jjramirezn
PR: peanutprotocol/peanut-ui#484
File: src/components/Cashout/Components/Initial.view.tsx:273-274
Timestamp: 2024-10-25T11:33:46.776Z
Learning: In the `InitialCashoutView` component (`src/components/Cashout/Components/Initial.view.tsx`), linked bank accounts should not generate error states, and the `ValidatedInput` component will clear any error messages if needed. Therefore, it's unnecessary to manually clear the error state when selecting or clearing linked bank accounts.

Applied to files:

  • src/components/AddWithdraw/DynamicBankAccountForm.tsx
📚 Learning: 2025-05-22T15:38:48.586Z
Learnt from: kushagrasarathe
PR: peanutprotocol/peanut-ui#869
File: src/app/(mobile-ui)/withdraw/page.tsx:82-88
Timestamp: 2025-05-22T15:38:48.586Z
Learning: The country-specific withdrawal route exists at src/app/(mobile-ui)/withdraw/[...country]/page.tsx and renders the AddWithdrawCountriesList component with flow="withdraw".

Applied to files:

  • src/components/AddWithdraw/DynamicBankAccountForm.tsx
🧬 Code graph analysis (1)
src/components/AddWithdraw/DynamicBankAccountForm.tsx (2)
src/hooks/useDebounce.ts (1)
  • useDebounce (9-23)
src/utils/bridge-accounts.utils.ts (1)
  • validateBic (73-89)
🔇 Additional comments (2)
src/components/AddWithdraw/DynamicBankAccountForm.tsx (2)

17-17: Import looks good.

Using the shared debounce hook here is appropriate.


80-80: LGTM on pulling watch from RHF.

Needed for BIC debouncing logic.

Comment on lines 381 to 391
if (!value || value.trim().length === 0) return 'BIC is required'

// Only validate if the value matches the debounced value (to prevent API calls on every keystroke)
if (value.trim() !== debouncedBicValue?.trim()) {
return true // Skip validation until debounced value is ready
}

setisCheckingBICValid(true)
const isValid = await validateBic(value.trim())
setisCheckingBICValid(false)
return isValid || 'Invalid BIC code'
Copy link
Contributor

@coderabbitai coderabbitai bot Sep 2, 2025

Choose a reason for hiding this comment

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

⚠️ Potential issue

Bug: returning true while debounce not settled can bypass BIC validation.

If the user blurs/submits within the debounce window, validate returns true, marking BIC valid without any API check. This can let invalid BICs through.

Apply:

-// Only validate if the value matches the debounced value (to prevent API calls on every keystroke)
-if (value.trim() !== debouncedBicValue?.trim()) {
-    return true // Skip validation until debounced value is ready
-}
-
-setisCheckingBICValid(true)
-const isValid = await validateBic(value.trim())
-setisCheckingBICValid(false)
+// Only validate once the debounced value matches. Until then, keep the field invalid.
+if (value.trim() !== debouncedBicValue?.trim()) {
+    return 'Validating BIC…'
+}
+
+setIsCheckingBICValid(true)
+let isValid: boolean
+try {
+    isValid = await validateBic(value.trim())
+} finally {
+    setIsCheckingBICValid(false)
+}
 return isValid || 'Invalid BIC code'

Also updates the setter casing per earlier comment.

📝 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 (!value || value.trim().length === 0) return 'BIC is required'
// Only validate if the value matches the debounced value (to prevent API calls on every keystroke)
if (value.trim() !== debouncedBicValue?.trim()) {
return true // Skip validation until debounced value is ready
}
setisCheckingBICValid(true)
const isValid = await validateBic(value.trim())
setisCheckingBICValid(false)
return isValid || 'Invalid BIC code'
if (!value || value.trim().length === 0) return 'BIC is required'
// Only validate once the debounced value matches. Until then, keep the field invalid.
if (value.trim() !== debouncedBicValue?.trim()) {
return 'Validating BIC…'
}
setIsCheckingBICValid(true)
let isValid: boolean
try {
isValid = await validateBic(value.trim())
} finally {
setIsCheckingBICValid(false)
}
return isValid || 'Invalid BIC code'
🤖 Prompt for AI Agents
In src/components/AddWithdraw/DynamicBankAccountForm.tsx around lines 381 to
391, the validator currently returns true when the debounced value hasn't
matched yet, which allows bypassing BIC validation if the user submits quickly;
change the logic to wait for debounce by returning a pending validation
indicator (e.g., return a Promise that performs validation once
debouncedBicValue matches) or explicitly trigger validation when value differs
from debounced value so the API check runs before resolving, ensure
setIsCheckingBICValid uses the corrected camelCase setter name, and finally
resolve to the validation result or the 'Invalid BIC code' message.

Copy link
Contributor

Choose a reason for hiding this comment

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

@Zishan-7 seems valid 👀

Copy link
Contributor

Choose a reason for hiding this comment

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

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

Comment on lines 381 to 391
if (!value || value.trim().length === 0) return 'BIC is required'

// Only validate if the value matches the debounced value (to prevent API calls on every keystroke)
if (value.trim() !== debouncedBicValue?.trim()) {
return true // Skip validation until debounced value is ready
}

setisCheckingBICValid(true)
const isValid = await validateBic(value.trim())
setisCheckingBICValid(false)
return isValid || 'Invalid BIC code'
Copy link
Contributor

Choose a reason for hiding this comment

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

@Zishan-7 seems valid 👀

@Zishan-7 Zishan-7 closed this Sep 5, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants