Skip to content

Update BookEvent.tsx#61

Open
nancy-verma780 wants to merge 1 commit into
niharika-mente:mainfrom
nancy-verma780:fix-booking-error
Open

Update BookEvent.tsx#61
nancy-verma780 wants to merge 1 commit into
niharika-mente:mainfrom
nancy-verma780:fix-booking-error

Conversation

@nancy-verma780
Copy link
Copy Markdown
Contributor

@nancy-verma780 nancy-verma780 commented Jun 6, 2026

Description

This PR resolves the issue where users received no visual feedback when a booking registration failed (e.g., due to duplicate entries in MongoDB) or when the server action was processing.

Changes Made:

  • Added error and isSubmitting local states using useState.
  • Updated handleSubmit to handle server response errors cleanly with try/catch/finally.
  • Disabled the email input field and submit button during active submissions.
  • Dynamically changed the button text to "Submitting..." during active processing.
  • Added a conditional error message element beneath the input field.

Closes #19

Summary by CodeRabbit

  • Bug Fixes
    • Improved event booking form submission with enhanced error handling and user feedback
    • Form now displays error messages when booking fails
    • Form inputs and submit button disabled during submission with "Submitting..." status indicator
    • Better prevention of duplicate bookings

@vercel
Copy link
Copy Markdown

vercel Bot commented Jun 6, 2026

@nancy-verma780 is attempting to deploy a commit to the niharika-mente's projects Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Jun 6, 2026

Need the big picture first? Review this PR in Change Stack to see what changed before going file by file.

Review Change Stack

📝 Walkthrough

Walkthrough

The BookEvent component now properly handles booking submission with user-facing error feedback and loading states. The form tracks submission status and validation errors, disables interactions during async operations, and displays descriptive error messages when booking fails.

Changes

Booking Form Error Handling and Loading States

Layer / File(s) Summary
Error handling, loading state, and form submission flow
components/BookEvent.tsx
State hooks added for error and isSubmitting flags. The handleSubmit function wraps booking creation in try/catch/finally to manage submission lifecycle: clears prior errors, sets loading while createBooking runs, sets submitted and captures PostHog event on success, and sets user-facing error messages on failure. Form inputs are disabled during submission, the submit button text changes to "Submitting...", and a red error message renders conditionally when an error is set.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested labels

SSoC26, Medium

Suggested reviewers

  • SatyamPandey-07
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Title check ❓ Inconclusive The title 'Update BookEvent.tsx' is vague and generic, using non-descriptive language that does not convey meaningful information about the specific changes made. Use a more descriptive title that highlights the main change, such as 'Add error handling and loading states to BookEvent form submission'.
✅ Passed checks (4 passed)
Check name Status Explanation
Description check ✅ Passed The description includes a summary of changes, an issue reference, and testing approach, largely following the template structure and providing sufficient context.
Linked Issues check ✅ Passed The code changes fully address all requirements from issue #19: error state handling, loading state management, disabled controls during submission, dynamic button text, and conditional error display.
Out of Scope Changes check ✅ Passed All changes in BookEvent.tsx are directly related to the error handling and loading state requirements defined in issue #19, with no extraneous modifications.
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

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 Biome (2.4.16)
components/BookEvent.tsx

File contains syntax errors that prevent linting: Line 63: expected ) but instead the file ends

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

components/BookEvent.tsx

Parsing error: ')' expected.


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.

Copy link
Copy Markdown

@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 (2)
components/BookEvent.tsx (2)

28-30: 💤 Low value

Optional: Log caught error for debugging.

The catch block captures network and exception errors but doesn't use the err parameter. While setting a generic user-facing message is appropriate for security, consider logging the actual error for diagnostics or capturing it with PostHog for debugging.

💡 Optional enhancement
   } catch (err) {
+    console.error('Booking submission error:', err);
+    posthog.captureException(err instanceof Error ? err : new Error(String(err)));
     setError("A network error occurred. Please try again.");
   } finally {
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@components/BookEvent.tsx` around lines 28 - 30, In the catch block in
BookEvent.tsx where you call setError("A network error occurred..."), also log
or capture the caught err for diagnostics: reference the err parameter and add a
diagnostic call (e.g., console.error(err) or PostHog.capture/your telemetry
utility) so the user-facing message remains generic while the real error is
recorded; ensure you use the existing err variable and do not expose its
contents to the UI.

26-26: PostHog captureException: string is allowed, but you’re losing the real error details.

posthog.captureException('Booking creation failed') matches PostHog’s captureException(error: unknown, ...) signature, so this won’t break typing—but it drops the useful context you already have (response.error and the caught err). Capture those instead (e.g., include response.error on the else path and capture err in the catch).

Suggested adjustment
     } else {
       setError(response.error || "An unexpected error occurred. Please try again.");
-      posthog.captureException('Booking creation failed');
+      posthog.captureException(new Error(`Booking creation failed: ${response.error || 'Unknown error'}`));
     }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@components/BookEvent.tsx` at line 26, Replace the plain string passed to
posthog.captureException with the actual error objects so you don't lose
context: in the error branch of the function call use
posthog.captureException(response.error, { message: 'Booking creation failed' })
(or include response.error when handling the non-OK response), and in the catch
block call posthog.captureException(err, { message: 'Booking creation threw' });
update the BookEvent.tsx locations where posthog.captureException is invoked to
reference response.error and err respectively instead of the static string.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@components/BookEvent.tsx`:
- Around line 44-51: Add the HTML required attribute to the email input in the
BookEvent component to enforce client-side non-empty validation: update the
<input> with id "email" (the one using value={email}, onChange={e =>
setEmail(e.target.value)} and disabled={isSubmitting}) to include required so
the browser prevents empty submissions before backend validation.
- Around line 4-5: The useState calls (useState, setError, setIsSubmitting) were
declared at module scope which violates the Rules of Hooks and precedes imports;
move those hook declarations inside the BookEvent function body so they are
executed during render. Locate the top-level const [error, setError] =
useState<string | null>(null) and const [isSubmitting, setIsSubmitting] =
useState(false) and cut/paste them into the start of the BookEvent component
function (immediately after the function signature) and remove the top-level
instances so imports remain at top-level and hooks run only inside the BookEvent
component.

---

Nitpick comments:
In `@components/BookEvent.tsx`:
- Around line 28-30: In the catch block in BookEvent.tsx where you call
setError("A network error occurred..."), also log or capture the caught err for
diagnostics: reference the err parameter and add a diagnostic call (e.g.,
console.error(err) or PostHog.capture/your telemetry utility) so the user-facing
message remains generic while the real error is recorded; ensure you use the
existing err variable and do not expose its contents to the UI.
- Line 26: Replace the plain string passed to posthog.captureException with the
actual error objects so you don't lose context: in the error branch of the
function call use posthog.captureException(response.error, { message: 'Booking
creation failed' }) (or include response.error when handling the non-OK
response), and in the catch block call posthog.captureException(err, { message:
'Booking creation threw' }); update the BookEvent.tsx locations where
posthog.captureException is invoked to reference response.error and err
respectively instead of the static string.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 17e8ddec-895f-4ba9-ac7b-7b11db0f73d7

📥 Commits

Reviewing files that changed from the base of the PR and between 7118b3e and 328e9cc.

📒 Files selected for processing (1)
  • components/BookEvent.tsx

Comment thread components/BookEvent.tsx
Comment on lines +4 to +5
const [error, setError] = useState<string | null>(null);
const [isSubmitting, setIsSubmitting] = useState(false);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Critical: React hooks called outside component function.

Lines 4-5 declare useState hooks at the module/top level, before the BookEvent component function is defined on line 9. This violates React's Rules of Hooks and will cause an immediate runtime crash with "Invalid hook call. Hooks can only be called inside the body of a function component."

Additionally, having imports on lines 6-7 after executable statements (lines 4-5) is invalid JavaScript syntax.

These hooks must be moved inside the BookEvent component function body.

🔧 Required fix: Move hooks inside component
 'use client';

 import {useState} from "react";
-const [error, setError] = useState<string | null>(null);
-const [isSubmitting, setIsSubmitting] = useState(false);
 import {createBooking} from "`@/lib/actions/booking.actions`";
 import posthog from "posthog-js";

 const BookEvent = ({ eventId, slug }: { eventId: string, slug: string;}) => {
     const [email, setEmail] = useState('');
     const [submitted, setSubmitted] = useState(false);
+    const [error, setError] = useState<string | null>(null);
+    const [isSubmitting, setIsSubmitting] = useState(false);

     const handleSubmit = async (e: React.FormEvent) => {
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@components/BookEvent.tsx` around lines 4 - 5, The useState calls (useState,
setError, setIsSubmitting) were declared at module scope which violates the
Rules of Hooks and precedes imports; move those hook declarations inside the
BookEvent function body so they are executed during render. Locate the top-level
const [error, setError] = useState<string | null>(null) and const [isSubmitting,
setIsSubmitting] = useState(false) and cut/paste them into the start of the
BookEvent component function (immediately after the function signature) and
remove the top-level instances so imports remain at top-level and hooks run only
inside the BookEvent component.

Comment thread components/BookEvent.tsx
Comment on lines +44 to +51
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
id="email"
placeholder="Enter your email address"
disabled={isSubmitting} // 1. Freeze input when submitting
/>
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Consider adding required attribute to email input.

The email input has type="email" for format validation but lacks the required attribute. Users can currently submit the form with an empty email, which will fail at the backend validation. Adding required would provide immediate client-side feedback and improve UX.

📋 Suggested enhancement
                 <input
                     type="email"
                     value={email}
                     onChange={(e) => setEmail(e.target.value)}
                     id="email"
                     placeholder="Enter your email address"
+                    required
                     disabled={isSubmitting}
                 />
📝 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
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
id="email"
placeholder="Enter your email address"
disabled={isSubmitting} // 1. Freeze input when submitting
/>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
id="email"
placeholder="Enter your email address"
required
disabled={isSubmitting} // 1. Freeze input when submitting
/>
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@components/BookEvent.tsx` around lines 44 - 51, Add the HTML required
attribute to the email input in the BookEvent component to enforce client-side
non-empty validation: update the <input> with id "email" (the one using
value={email}, onChange={e => setEmail(e.target.value)} and
disabled={isSubmitting}) to include required so the browser prevents empty
submissions before backend validation.

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.

Issue : [BUG/UX] Booking Form Error Handling & Loading States

1 participant