Skip to content

Fix: Add error handling for JSON.parse in trackpad component#319

Open
upendra512 wants to merge 1 commit intoAOSSIE-Org:mainfrom
upendra512:fix/json-parse-error-handling-308
Open

Fix: Add error handling for JSON.parse in trackpad component#319
upendra512 wants to merge 1 commit intoAOSSIE-Org:mainfrom
upendra512:fix/json-parse-error-handling-308

Conversation

@upendra512
Copy link

@upendra512 upendra512 commented Mar 17, 2026

Description

Fixes Issue #308 - JSON.parse without try/catch crashes trackpad component

Changes

  • Added try/catch error handling around JSON.parse() when reading rein_invert from localStorage
  • Prevents component crash when localStorage contains malformed JSON data
  • Returns safe default value (false) on parsing error

Testing

  • ? Tested with valid localStorage data
  • ? Tested with malformed JSON data - no crash
  • ? Tested with null/undefined localStorage - returns default

Related Issue

Closes #308


First-time contributor ?? - Excited to contribute to AOSSIE!

Summary by CodeRabbit

Release Notes

  • Bug Fixes
    • Improved stability of trackpad scroll inversion settings by adding robust error handling for corrupted or missing configuration data, preventing potential application errors.

Add error handling for JSON.parse when reading 'rein_invert' from
localStorage to prevent component crashes on malformed data.

Fixes AOSSIE-Org#308

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 17, 2026

Walkthrough

The trackpad component's invertScroll initialization was hardened to prevent crashes from malformed JSON data in localStorage. A try/catch block now wraps JSON.parse, returning false on parse errors or missing data, eliminating unhandled exceptions while preserving valid JSON handling.

Changes

Cohort / File(s) Summary
Error Handling
src/routes/trackpad.tsx
Added try/catch wrapper around JSON.parse for rein_invert localStorage value to gracefully handle invalid JSON data and missing values, preventing component crashes.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Suggested labels

Typescript Lang

Poem

🐰 A rabbit's ode to safer code—
Where JSON parse no longer load,
With try and catch to catch the fall,
No crashes now—we've fixed it all! 🎉

🚥 Pre-merge checks | ✅ 3 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Description check ❓ Inconclusive The description addresses the linked issue (#308), explains the changes made, and includes testing notes. However, it does not follow the repository's detailed template structure with functional verification checklist items. Consider using the repository's full PR template with functional verification checkboxes to ensure comprehensive documentation and testing coverage verification.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically summarizes the main change: adding error handling for JSON.parse in the trackpad component.
Linked Issues check ✅ Passed The code changes directly address the requirement in Issue #308 by wrapping JSON.parse in a try/catch block to handle malformed localStorage data safely.
Out of Scope Changes check ✅ Passed All changes are focused on the specific issue: adding error handling to JSON.parse for the rein_invert localStorage value in trackpad.tsx, with no unrelated modifications.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
📝 Coding Plan
  • Generate coding plan for human review comments

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.

Tip

CodeRabbit can use oxc to improve the quality of JavaScript and TypeScript code reviews.

Add a configuration file to your project to customize how CodeRabbit runs oxc.

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

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/routes/trackpad.tsx`:
- Around line 33-41: The useState initializer for invertScroll in the Trackpad
component currently returns JSON.parse(s) directly which can yield non-boolean
and widen the state to any; change the state to an explicit boolean type (e.g.,
useState<boolean>) and guard the parsed value so only a true boolean is accepted
(parse, check typeof parsed === "boolean", and return parsed, otherwise return
false) while preserving the try/catch fallback to false; update references to
the invertScroll state accordingly.
🪄 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: ASSERTIVE

Plan: Pro

Run ID: af1013ac-2b55-4222-bef5-224496df20e4

📥 Commits

Reviewing files that changed from the base of the PR and between 25b2382 and d6189e4.

📒 Files selected for processing (1)
  • src/routes/trackpad.tsx

Comment on lines 33 to +41
const [invertScroll] = useState(() => {
if (typeof window === "undefined") return false
const s = localStorage.getItem("rein_invert")
return s ? JSON.parse(s) : false
if (!s) return false
try {
return JSON.parse(s)
} catch {
return false
}
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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify expected type at hook boundary and inspect current state initialization.
fd 'useTrackpadGesture\.(ts|tsx)$' --exec sed -n '1,220p' {}
rg -nP -C3 'const \[invertScroll\]\s*=\s*useState' src/routes/trackpad.tsx

Repository: AOSSIE-Org/Rein

Length of output: 6403


🏁 Script executed:

head -10 src/routes/trackpad.tsx | cat -n

Repository: AOSSIE-Org/Rein

Length of output: 723


Constrain parsed localStorage value to boolean and type the state explicitly.

Line 38 returns JSON.parse(s) directly, which makes invertScroll effectively any and accepts non-boolean JSON (e.g., "1" or {}). Keep the crash fix, but enforce a boolean guard.

Proposed fix
-	const [invertScroll] = useState(() => {
+	const [invertScroll] = useState<boolean>(() => {
 		if (typeof window === "undefined") return false
 		const s = localStorage.getItem("rein_invert")
 		if (!s) return false
 		try {
-			return JSON.parse(s)
+			const parsed: unknown = JSON.parse(s)
+			return typeof parsed === "boolean" ? parsed : false
 		} catch {
 			return false
 		}
 	})

This addresses the TypeScript guideline: "Avoid 'any', use explicit types".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/routes/trackpad.tsx` around lines 33 - 41, The useState initializer for
invertScroll in the Trackpad component currently returns JSON.parse(s) directly
which can yield non-boolean and widen the state to any; change the state to an
explicit boolean type (e.g., useState<boolean>) and guard the parsed value so
only a true boolean is accepted (parse, check typeof parsed === "boolean", and
return parsed, otherwise return false) while preserving the try/catch fallback
to false; update references to the invertScroll state accordingly.

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.

[Bug]: JSON.parse without try/catch crashes trackpad component

2 participants