Skip to content

Conversation

@sarthakNITT
Copy link
Contributor

@sarthakNITT sarthakNITT commented Dec 6, 2025

Description

  • Added proper error handling to fetch calls in Feedback and NewsletterSubscribe components
  • Replaced .then() chains with async/await + try/catch for cleaner and safer logic
  • Ensures network failures are caught and correct error UI is shown

Summary by CodeRabbit

  • Refactor
    • Modernized form submission handling and error management across subscription/feedback flows to make submissions more reliable.
  • Bug Fixes
    • Improved handling of failed submissions and unexpected errors to reduce user-facing submission failures.

✏️ Tip: You can customize this high-level summary in your review settings.

@netlify
Copy link

netlify bot commented Dec 6, 2025

Deploy Preview for asyncapi-website ready!

Built without sensitive environment variables

Name Link
🔨 Latest commit d013e5d
🔍 Latest deploy log https://app.netlify.com/projects/asyncapi-website/deploys/6933fcf74f8d850008a5ddcc
😎 Deploy Preview https://deploy-preview-4687--asyncapi-website.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 6, 2025

Walkthrough

Two React components switch from promise chains to async/await and add try/catch around fetch, checking response status and handling response.json() with explicit success/error state updates.

Changes

Cohort / File(s) Summary
Async/await fetch refactor
components/Feedback.tsx, components/NewsletterSubscribe.tsx
Converted .then()/.catch() promise chains to async/await with try/catch. Await fetch and response.json(), check non-200 status to set error state, and set submitted/success state on 200 responses. No exported signatures changed.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

  • Same refactor pattern applied to both files; low logic density.
  • Review focus: correct awaiting of response.json(), preserved state updates, and appropriate error messages.

Possibly related issues

Suggested labels

ready-to-merge

Suggested reviewers

  • derberg
  • sambhavgupta0705
  • anshgoyalevil
  • Mayaleeeee
  • asyncapi-bot-eve

Poem

🐰 I hopped through code, turned chains to await,

Try caught the winds and made errors abate,
Responses now parsed in a tidy queue,
A cleaner run — a carrot-chewed review!

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: converting fetch calls from promise chains to async/await with try/catch for improved error handling in two components.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

@asyncapi-bot
Copy link
Contributor

asyncapi-bot commented Dec 6, 2025

⚡️ Lighthouse report for the changes in this PR:

Category Score
🔴 Performance 40
🟢 Accessibility 98
🟢 Best practices 92
🟢 SEO 100
🔴 PWA 33

Lighthouse ran on https://deploy-preview-4687--asyncapi-website.netlify.app/

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 (2)
components/Feedback.tsx (1)

39-57: Async/await refactor is correct; consider response.ok and dropping unused JSON parsing

The new async/await + try/catch flow is functionally sound and correctly surfaces network failures via setError(true). To tighten it up:

  • Prefer response.ok instead of response.status === 200 so that any 2xx success is treated as success.
  • Since the JSON body is not used, await response.json() is unnecessary and may incorrectly flip a successful request into an error if the body is empty or non‑JSON.

You could simplify to:

    try {
      const response = await fetch('/.netlify/functions/github_discussions', {
        method: 'POST',
        body: JSON.stringify(data),
        headers: {
          'Content-Type': 'application/json'
        }
      });

-     if (response.status === 200) {
-       setSubmitted(true);
-     } else {
-       setError(true);
-     }
-
-     await response.json();
+     if (!response.ok) {
+       setError(true);
+       return;
+     }
+
+     setSubmitted(true);
    } catch (err) {
      setError(true);
    }

This keeps the intended behavior while avoiding a potential false error state from JSON parsing. As per coding guidelines, this is a good use of try/catch since it directly controls graceful UI degradation.

components/NewsletterSubscribe.tsx (1)

67-94: Async submit logic looks good; refine status check and JSON handling

The conversion to async + try/catch correctly drives the form status and handles network failures by setting FormStatus.ERROR. A couple of small improvements:

  • Use res.ok instead of res.status === 200 to treat all 2xx responses as success:
    if (!res.ok) {
      setFormStatus(FormStatus.ERROR);
      return;
    }
    setFormStatus(FormStatus.SUCCESS);
  • Since the response body is not used, await res.json() is redundant and may incorrectly flip a success into an error if the body is empty or invalid JSON. You can safely remove it.

These tweaks keep the UX the same in the happy path while making the handler more robust.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a677dc6 and e52851f.

📒 Files selected for processing (2)
  • components/Feedback.tsx (1 hunks)
  • components/NewsletterSubscribe.tsx (2 hunks)
🧰 Additional context used
🧠 Learnings (1)
📓 Common learnings
Learnt from: JeelRajodiya
Repo: asyncapi/website PR: 3423
File: scripts/index.ts:29-31
Timestamp: 2025-03-16T15:55:44.257Z
Learning: In the AsyncAPI codebase, adding try-catch blocks around function calls is unnecessary when the only purpose is to add context to the error message, as errors will be thrown from the functions themselves with full stack traces that provide adequate context. Try-catch blocks should only be added when there's a need for graceful degradation, partial success behavior, or specific error handling logic.
Learnt from: anshgoyalevil
Repo: asyncapi/website PR: 3557
File: scripts/markdown/check-editlinks.js:58-59
Timestamp: 2025-01-08T15:15:00.759Z
Learning: In the AsyncAPI codebase, batch processing operations (like in the Dashboard script and check-editlinks.js) follow a sequential pattern using await in loops, which is the preferred approach for maintaining consistency across the codebase.
Learnt from: sagarkori143
Repo: asyncapi/website PR: 4192
File: npm/runners/build-pages-runner.ts:7-14
Timestamp: 2025-06-19T13:51:27.459Z
Learning: In the AsyncAPI website build system, individual runner functions use try-catch blocks that rethrow errors to maintain consistent error boundaries, while the top-level orchestrator in npm/index.ts provides meaningful error logging with task-specific context using logger.error(`Error building ${taskName}:`, error). This separation of concerns allows for clean error handling at different architectural layers.
Learnt from: sagarkori143
Repo: asyncapi/website PR: 4192
File: npm/runners/build-newsroom-videos-runner.ts:8-15
Timestamp: 2025-06-19T13:49:29.796Z
Learning: In the AsyncAPI website modularization project, error handling is centralized in the top-level orchestrator function (npm/index.ts) with comprehensive logging and context. Individual runner functions in npm/runners/ are kept simple and let errors propagate naturally to the centralized handler, avoiding redundant try-catch blocks that only rethrow errors.
Learnt from: sagarkori143
Repo: asyncapi/website PR: 0
File: :0-0
Timestamp: 2025-06-20T14:47:22.389Z
Learning: The AsyncAPI website modularization PR uses Promise.allSettled for parallel execution of build tasks, which provides better performance and fault isolation compared to sequential execution.
🪛 GitHub Actions: PR testing - if Node project
components/Feedback.tsx

[error] 47-47: prettier/prettier: Delete spaces before line break or trailing spaces.


[error] 47-47: no-trailing-spaces: Trailing spaces not allowed.


[error] 53-53: prettier/prettier: Delete spaces before line break or trailing spaces.


[error] 53-53: no-trailing-spaces: Trailing spaces not allowed.

components/NewsletterSubscribe.tsx

[error] 84-84: prettier/prettier: Delete spaces before line break or trailing spaces.


[error] 84-84: no-trailing-spaces: Trailing spaces not allowed.


[error] 90-90: prettier/prettier: Delete spaces before line break or trailing spaces.


[error] 90-90: no-trailing-spaces: Trailing spaces not allowed.

⏰ Context from checks skipped due to timeout of 180000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: cypress-run
  • GitHub Check: Lighthouse CI

@codecov
Copy link

codecov bot commented Dec 6, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (a677dc6) to head (d013e5d).
⚠️ Report is 4 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #4687   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           22        22           
  Lines          799       799           
  Branches       146       146           
=========================================
  Hits           799       799           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

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

🧹 Nitpick comments (1)
components/NewsletterSubscribe.tsx (1)

67-94: Drop unused res.json() (or gate it) to avoid unnecessary failures

The async/await + try/catch rewrite looks good and correctly flips the form status on HTTP and network errors. One minor improvement:

  • await res.json(); is called unconditionally, but the parsed body is never used.
  • If the backend ever returns non‑JSON (even with 200), this will throw and push the form into the ERROR state via the catch, even though the subscription might have succeeded.

Since you don’t currently consume the response body, you can safely remove the parse:

-      if (res.status === 200) {
-        setFormStatus(FormStatus.SUCCESS);
-      } else {
-        setFormStatus(FormStatus.ERROR);
-      }
-
-      await res.json();
+      if (res.status === 200) {
+        setFormStatus(FormStatus.SUCCESS);
+      } else {
+        setFormStatus(FormStatus.ERROR);
+      }

If you later need the payload, consider only parsing it on res.ok (or status === 200) and optionally guarding the parse with its own try/catch so you can handle “successful but malformed JSON” separately from network failures.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e52851f and 42f30e5.

📒 Files selected for processing (2)
  • components/Feedback.tsx (1 hunks)
  • components/NewsletterSubscribe.tsx (2 hunks)
⏰ Context from checks skipped due to timeout of 180000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: cypress-run

Comment on lines +39 to +56
try {
const response = await fetch('/.netlify/functions/github_discussions', {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
});

if (response.status === 200) {
setSubmitted(true);
}
if (response.status !== 200) {
} else {
setError(true);
}
response.json();
});
await response.json();
} catch (err) {
setError(true);
}
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 | 🟡 Minor

Align success/error state with JSON parsing and remove unused response.json()

The new async/await + try/catch structure is a good improvement, but there’s a subtle edge case:

  • For a 200 response, you call setSubmitted(true) and then await response.json().
  • If response.json() throws (e.g., invalid JSON body), the catch runs and setError(true) is called.
  • Final state is submitted === true and error === true, and because the render checks if (submitted) before if (error), the user sees the success UI even though an error occurred.

Since the parsed body is not used, this extra await response.json() only introduces this failure mode without adding value.

Consider simplifying to something like:

-      if (response.status === 200) {
-        setSubmitted(true);
-      } else {
-        setError(true);
-      }
-      await response.json();
+      if (response.status === 200) {
+        setSubmitted(true);
+      } else {
+        setError(true);
+      }

Or, if you later need the body, only parse it when required and handle parse failures in a way that keeps submitted/error consistent with the UI you want.

📝 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
try {
const response = await fetch('/.netlify/functions/github_discussions', {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
});
if (response.status === 200) {
setSubmitted(true);
}
if (response.status !== 200) {
} else {
setError(true);
}
response.json();
});
await response.json();
} catch (err) {
setError(true);
}
try {
const response = await fetch('/.netlify/functions/github_discussions', {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
});
if (response.status === 200) {
setSubmitted(true);
} else {
setError(true);
}
} catch (err) {
setError(true);
}
🤖 Prompt for AI Agents
In components/Feedback.tsx around lines 39 to 56, the code sets submitted=true
before awaiting response.json(), so if JSON parsing fails the catch flips
error=true and leaves submitted=true (showing success and error); remove the
unused await response.json() (or if you need the body, await and parse it before
calling setSubmitted, catching parse errors and setting setError(true) instead
of setSubmitted) so submitted and error remain mutually consistent.

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.

2 participants