Skip to content

fix: UserPreferences.getBool not parsing JSON-string booleans#7510

Open
Rohit3523 wants to merge 3 commits into
developfrom
fix/in-app-vibration-toggle
Open

fix: UserPreferences.getBool not parsing JSON-string booleans#7510
Rohit3523 wants to merge 3 commits into
developfrom
fix/in-app-vibration-toggle

Conversation

@Rohit3523

@Rohit3523 Rohit3523 commented Jul 23, 2026

Copy link
Copy Markdown
Member

Proposed changes

Fix getBool in UserPreferences to correctly read booleans stored as JSON strings by useUserPreferences<boolean>. Previously, getBool only used native MMKV getBoolean, which couldn't parse "false" (stored as a JSON string) and would return null/undefined. The fallback now tries getString + JSON.parse first, then falls back to native getBoolean.

This caused the haptic feedback on reconnect (from RoomView.hapticFeedback) to ignore NOTIFICATION_IN_APP_VIBRATION toggle — vibration played for every pending message replayed on DDP reconnect even when the toggle was off.

Issue(s)

https://rocketchat.atlassian.net/browse/SUP-1079

How to test or reproduce

  1. Go to Settings → Notifications → disable "Vibrate from new messages"
  2. Disconnect from network (airplane mode)
  3. Reconnect — observe no vibration for replayed messages

Screenshots

Types of changes

  • Bugfix (non-breaking change which fixes an issue)
  • Improvement (non-breaking change which improves a current function)
  • New feature (non-breaking change which adds functionality)
  • Documentation update (if none of the other choices apply)

Checklist

  • I have read the CONTRIBUTING doc
  • I have signed the CLA
  • Lint and unit tests pass locally with my changes
  • I have added tests that prove my fix is effective or that my feature works (if applicable)
  • I have added necessary documentation (if applicable)
  • Any dependent changes have been merged and published in downstream modules

Further comments

Summary by CodeRabbit

  • Bug Fixes

    • Improved boolean preference retrieval by correctly handling values saved as JSON-formatted strings (e.g., "true" / "false").
    • If the stored value is present but not a boolean (or invalid JSON), the preference now resolves to null, while existing fallback behavior remains intact.
  • Tests

    • Added Jest coverage for both valid JSON boolean strings and invalid/non-boolean stored values returning null.

@coderabbitai

coderabbitai Bot commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

UserPreferences.getBool parses boolean values stored as JSON strings before falling back to boolean retrieval. Tests cover valid boolean strings and invalid or non-boolean values.

Changes

Boolean preference parsing

Layer / File(s) Summary
String boolean parsing and coverage
app/lib/methods/userPreferences.ts, app/lib/methods/userPreferences.test.ts
getBool parses JSON-string booleans, returns null for parse or type mismatches, retains the existing boolean fallback, and tests valid and invalid representations.

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related PRs

Suggested labels: type: bug

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly states the main fix: UserPreferences.getBool now parses JSON-string booleans.

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (2)
app/lib/methods/userPreferences.ts (1)

109-109: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use a descriptive name for the stored value.

Rename str to storedString or stringValue so its role in the preference parsing flow is clear.

Suggested rename
-			const str = this.mmkv.getString(key);
-			if (str !== undefined) {
+			const storedString = this.mmkv.getString(key);
+			if (storedString !== undefined) {
 				try {
-					const parsed: unknown = JSON.parse(str);
+					const parsed: unknown = JSON.parse(storedString);

As per coding guidelines, variable names should clearly convey their purpose.

🤖 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 `@app/lib/methods/userPreferences.ts` at line 109, Rename the local variable
`str` in the user preference parsing flow to `storedString` or `stringValue`,
and update all references within its scope to preserve the existing behavior.

Source: Coding guidelines

app/lib/methods/userPreferences.test.ts (1)

11-16: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Cover the invalid and non-boolean JSON branches.

The new test covers true and false, but not the required null behavior for values such as numbers, objects, null, or malformed JSON.

Suggested regression cases
+	it('getBool returns null for non-boolean or invalid JSON strings', () => {
+		for (const value of ['1', 'null', '{}', 'not-json']) {
+			userPreferences.setString('k', value);
+			expect(userPreferences.getBool('k')).toBeNull();
+		}
+	});

Based on the PR objective, non-boolean parsed values must return null.

🤖 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 `@app/lib/methods/userPreferences.test.ts` around lines 11 - 16, Extend the
getBool test in userPreferences.test.ts to cover JSON strings that parse to
non-boolean values, including a number, object, and null, plus malformed JSON.
Assert that getBool('k') returns null for each case while preserving the
existing true and false assertions.
🤖 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.

Nitpick comments:
In `@app/lib/methods/userPreferences.test.ts`:
- Around line 11-16: Extend the getBool test in userPreferences.test.ts to cover
JSON strings that parse to non-boolean values, including a number, object, and
null, plus malformed JSON. Assert that getBool('k') returns null for each case
while preserving the existing true and false assertions.

In `@app/lib/methods/userPreferences.ts`:
- Line 109: Rename the local variable `str` in the user preference parsing flow
to `storedString` or `stringValue`, and update all references within its scope
to preserve the existing behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: eb1eea1f-2f21-400d-b99c-76cc3ced9b97

📥 Commits

Reviewing files that changed from the base of the PR and between 1d9b5cc and 072e027.

📒 Files selected for processing (2)
  • app/lib/methods/userPreferences.test.ts
  • app/lib/methods/userPreferences.ts
📜 Review details
⏰ Context from checks skipped due to timeout. (1)
  • GitHub Check: ESLint and Test / run-eslint-and-test
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{js,ts,jsx,tsx}: Use descriptive names for functions, variables, and classes that clearly convey their purpose
Write comments that explain the 'why' behind code decisions, not the 'what'
Keep functions small and focused on a single responsibility
Use const by default, let when reassignment is needed, and avoid var
Prefer async/await over .then() chains for handling asynchronous operations
Use explicit error handling with try/catch blocks for async operations
Avoid deeply nested code; refactor complex logic into helper functions

Files:

  • app/lib/methods/userPreferences.test.ts
  • app/lib/methods/userPreferences.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use TypeScript for type safety; add explicit type annotations to function parameters and return types
Prefer interfaces over type aliases for defining object shapes in TypeScript
Use enums for sets of related constants rather than magic strings or numbers

Use TypeScript strict mode; resolve application imports relative to the app/ base URL.

Files:

  • app/lib/methods/userPreferences.test.ts
  • app/lib/methods/userPreferences.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (CLAUDE.md)

Follow the repository Prettier style: tabs, single quotes, 130-character width, no trailing commas, omitted arrow-function parentheses where allowed, and same-line brackets.

Files:

  • app/lib/methods/userPreferences.test.ts
  • app/lib/methods/userPreferences.ts
**/*.test.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (CLAUDE.md)

Run Jest tests with TZ=UTC to ensure deterministic timezone-dependent test behavior.

Files:

  • app/lib/methods/userPreferences.test.ts
🧠 Learnings (2)
📚 Learning: 2026-04-30T17:07:51.020Z
Learnt from: diegolmello
Repo: RocketChat/Rocket.Chat.ReactNative PR: 7274
File: app/lib/services/voip/MediaCallEvents.ts:0-0
Timestamp: 2026-04-30T17:07:51.020Z
Learning: In this Rocket.Chat React Native codebase, the ESLint rule `no-void: error` is enforced. When you see a promise returned from an async call that is not awaited (a “floating promise”), do not silence it with the `void somePromise()` pattern. Instead, handle the promise explicitly by attaching `.catch(...)` (or otherwise awaiting/handling the error) so unhandled-rejection risks are addressed in a way that satisfies the existing ESLint configuration.

Applied to files:

  • app/lib/methods/userPreferences.test.ts
  • app/lib/methods/userPreferences.ts
📚 Learning: 2026-06-25T18:37:25.526Z
Learnt from: diegolmello
Repo: RocketChat/Rocket.Chat.ReactNative PR: 7434
File: app/views/ScreenLockConfigView.test.tsx:16-22
Timestamp: 2026-06-25T18:37:25.526Z
Learning: In Rocket.Chat ReactNative tests that mock selectors for `useAppSelector`, don’t require the mocked selector input to be typed as `IApplicationState` when the fixture only includes a partial Redux state slice (e.g., only `server` and `settings`). Requiring the full `IApplicationState` type in that scenario forces unsafe `as IApplicationState` casts and undermines type-safety. For these narrowly scoped selector-mock fixtures, use a less strict type (e.g., `any`) to keep the mock focused on the slice under test.

Applied to files:

  • app/lib/methods/userPreferences.test.ts
🔇 Additional comments (2)
app/lib/methods/userPreferences.ts (1)

110-117: LGTM!

app/lib/methods/userPreferences.test.ts (1)

11-16: 📐 Maintainability & Code Quality

No change needed for this test command.

The current snippet only covers JSON-parsed booleans and does not touch timezone-sensitive behavior; the repository’s test script already enforces TZ=UTC.

			> Likely an incorrect or invalid review comment.

@github-actions

Copy link
Copy Markdown

@github-actions

Copy link
Copy Markdown

iOS Build Available

Rocket.Chat 4.75.0.109402

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant