Skip to content

[feature/db] Implement data persistence layer for creating and editing alarms - #2

Merged
HoweiAY merged 8 commits into
mainfrom
feature/db
Jul 31, 2026
Merged

HoweiAY merged 8 commits into
mainfrom
feature/db

Conversation

@HoweiAY

@HoweiAY HoweiAY commented Jul 30, 2026 •

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

  • New Features
    • Alarms are now saved locally and remain available between app sessions.
    • Creating, editing, enabling, disabling, and deleting alarms now updates saved data.
    • Added support for alarm schedules, task settings, difficulty, sound preferences, and snooze status.
  • Bug Fixes
    • Alarm lists now refresh automatically after changes.
    • Added an empty-state screen with a shortcut to create an alarm.
    • Improved handling of optional custom sounds and alarm identifiers.
    • Added retry options and clearer error messages when alarms fail to load.

@coderabbitai

coderabbitai Bot commented Jul 30, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: cc8f8452-a3a1-4e7c-ae5d-6bdcc75b2f00

📥 Commits

Reviewing files that changed from the base of the PR and between 0fe348a and 62d45f8.

📒 Files selected for processing (3)
  • src/app/(main)/create-alarm/[alarmId].tsx
  • src/hooks/useAlarmById.ts
  • src/store/alarmStore.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/store/alarmStore.ts
  • src/hooks/useAlarmById.ts

📝 Walkthrough

Walkthrough

Changes

The PR replaces mock alarm data with a Drizzle/Expo SQLite database, generated migrations, and a Zustand store. Alarm conversion helpers, form persistence, screen CRUD actions, lifecycle loading, and empty and error states are added.

Alarm persistence

Layer / File(s) Summary
SQLite schema and migration setup
AGENTS.md, app.json, babel.config.js, drizzle*, metro.config.js, package.json, src/data/schema.ts, src/data/db.ts, src/data/types.ts
Defines the alarms table, migration configuration and artifacts, Expo SQLite integration, SQL bundling configuration, and string/nullability updates to Alarm.
Alarm conversion and persistence store
src/data/constants.ts, src/data/conversions.ts, src/store/alarmStore.ts
Converts domain alarm values to storage values and implements database-backed Zustand loading, subscriptions, CRUD operations, and lookup methods.
Alarm form persistence
src/hooks/useCreateAlarmForm.ts
Builds drafts without identifiers, handles nullable sounds, and persists new or edited alarms through the store.
Alarm screen and hook integration
src/app/_layout.tsx, src/app/(main)/index.tsx, src/hooks/useAlarmById.ts, src/app/(main)/create-alarm/[alarmId].tsx
Loads alarms from the store, persists screen actions, derives individual alarms reactively, and renders empty and loading-error states.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant RootLayout
  participant useAlarmStore
  participant dbReady
  participant SQLiteAlarms
  RootLayout->>useAlarmStore: loadAlarms()
  useAlarmStore->>dbReady: await database migrations
  useAlarmStore->>SQLiteAlarms: fetch ordered alarms
  SQLiteAlarms-->>useAlarmStore: alarm rows
  useAlarmStore-->>RootLayout: populated alarm state
Loading

Possibly related PRs

  • HoweiAY/brainly_alarm_expo#1: Provides the initial alarm UI, mock data, and placeholder hook flows replaced by this persistence integration.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the pull request’s main change: adding persistence for creating and editing alarms.
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.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/db

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 5

🧹 Nitpick comments (2)
src/hooks/useCreateAlarmForm.ts (1)

165-166: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

New comments added to a .ts file.

Per coding guidelines, comments shouldn't be added unless explicitly requested. These two "Seam" markers appear to be new additions in this diff.

As per coding guidelines, "Do not add comments unless explicitly requested; match the existing code style" (**/*.{ts,tsx}).

Also applies to: 192-192

🤖 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 `@src/hooks/useCreateAlarmForm.ts` around lines 165 - 166, Remove the newly
added “Seam 2” and corresponding “Seam” marker comments from the
useCreateAlarmForm hook, leaving the surrounding implementation and dependency
array unchanged.

Source: Coding guidelines

src/hooks/useAlarmById.ts (1)

5-16: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Narrow useAlarmById to string ids

Alarm.id is always a string, and the only caller passes alarmId as a string route param, so the number union member is unnecessary.

🤖 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 `@src/hooks/useAlarmById.ts` around lines 5 - 16, Update the useAlarmById
hook’s id parameter to accept only string (plus null/undefined), and remove the
number union from its type while preserving the existing lookup and null
handling.
🤖 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 `@AGENTS.md`:
- Line 28: Update the Persistence guidance in AGENTS.md to retain the npm run
db:generate requirement while removing the instruction to commit its output;
instead, state that generated artifacts should be included when requested,
consistent with the repository-wide no-commit rule.

In `@src/app/`(main)/index.tsx:
- Around line 49-56: Update both turnAllOnOff and performDelete to handle bulk
store-operation failures: start the per-alarm update/delete calls in parallel,
await them with failure handling, and prevent rejected promises from escaping
their onPress/void callers. Ensure performDelete resets selectedIds and
editEnabled regardless of whether an operation fails, while preserving the
existing success behavior and reporting failures appropriately.
- Around line 43-47: Update toggleEnabled to handle promise rejection from
useAlarmStore.getState().updateAlarm: attach error handling that reports the
failure to the user through the existing UI feedback mechanism, while preserving
the current enabled-state toggle behavior.

In `@src/hooks/useCreateAlarmForm.ts`:
- Around line 183-200: Update the persist function in the alarm save flow so
insertAlarm/updateAlarm failures are surfaced to the user instead of only
logged, and move router.back() out of finally so navigation occurs only after
persistence succeeds. Preserve the existing success behavior and error details
while keeping the failure path on the current form.

In `@src/store/alarmStore.ts`:
- Around line 43-67: Prevent concurrent initialization in loadAlarms by adding a
synchronous in-flight guard that is set before starting the asynchronous init
work and cleared when initialization completes or fails. Update init/loadAlarms
around the existing _disposer check so only one dbReady/fetchAlarms chain can
create the SQLite listener, while preserving disposer cleanup and allowing
retries after failure.

---

Nitpick comments:
In `@src/hooks/useAlarmById.ts`:
- Around line 5-16: Update the useAlarmById hook’s id parameter to accept only
string (plus null/undefined), and remove the number union from its type while
preserving the existing lookup and null handling.

In `@src/hooks/useCreateAlarmForm.ts`:
- Around line 165-166: Remove the newly added “Seam 2” and corresponding “Seam”
marker comments from the useCreateAlarmForm hook, leaving the surrounding
implementation and dependency array unchanged.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 1d5169f4-cacf-4a9a-b3a0-2216020c6665

📥 Commits

Reviewing files that changed from the base of the PR and between 5ca1e67 and 1b63224.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (21)
  • AGENTS.md
  • app.json
  • babel.config.js
  • drizzle.config.ts
  • drizzle/0000_large_vulture.sql
  • drizzle/meta/0000_snapshot.json
  • drizzle/meta/_journal.json
  • drizzle/migrations.js
  • metro.config.js
  • package.json
  • src/app/(main)/index.tsx
  • src/app/_layout.tsx
  • src/data/constants.ts
  • src/data/conversions.ts
  • src/data/db.ts
  • src/data/mockAlarms.ts
  • src/data/schema.ts
  • src/data/types.ts
  • src/hooks/useAlarmById.ts
  • src/hooks/useCreateAlarmForm.ts
  • src/store/alarmStore.ts
💤 Files with no reviewable changes (1)
  • src/data/mockAlarms.ts

Comment thread AGENTS.md Outdated
Comment thread src/app/(main)/index.tsx
Comment thread src/app/(main)/index.tsx
Comment thread src/hooks/useCreateAlarmForm.ts
Comment thread src/store/alarmStore.ts
HoweiAY added 3 commits July 31, 2026 17:59
Add a synchronous _initializing guard in init/loadAlarms so only one
dbReady/fetchAlarms chain can register the SQLite change listener,
while preserving disposer cleanup and allowing retries after failure.
Also align AGENTS.md persistence guidance with the no-commit rule.
Home screen: run turnAllOnOff/performDelete updates in parallel via
Promise.allSettled, report failures via Alert, and reset edit state
regardless of delete errors. toggleEnabled now catches rejections.
useCreateAlarmForm: report persist failures to the user and only
navigate back on success.
Drop the unused number union from useAlarmById's id parameter (id is
always string from the route). Remove Seam 1/2 marker comments from
useCreateAlarmForm per the no-comments guideline.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/hooks/useAlarmById.ts (1)

18-19: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Expose initialization failure instead of reporting permanent loading.

If dbReady or fetchAlarms() fails, useAlarmStore sets loading to false but leaves loaded as false. This hook then returns loading: true forever while it remains mounted.

Expose an initialization error from useAlarmStore and consume it here, or define a terminal failure state that the UI can handle. Add a failure-path test.

🤖 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 `@src/hooks/useAlarmById.ts` around lines 18 - 19, Update useAlarmById and
useAlarmStore so initialization failures from dbReady or fetchAlarms are exposed
as a terminal error state instead of leaving loaded false and reporting
permanent loading. Have the hook return that error alongside alarm/loading, and
add a test covering the failed initialization path.
🤖 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 `@src/hooks/useAlarmById.ts`:
- Line 5: Update useAlarmById so alarm-store initialization failures cannot
leave loaded false while loading remains true; add an explicit initialization
error state or mark loading complete in the failure path, and expose the
resulting state consistently so the edit screen exits “Loading alarm…” instead
of hanging.

---

Outside diff comments:
In `@src/hooks/useAlarmById.ts`:
- Around line 18-19: Update useAlarmById and useAlarmStore so initialization
failures from dbReady or fetchAlarms are exposed as a terminal error state
instead of leaving loaded false and reporting permanent loading. Have the hook
return that error alongside alarm/loading, and add a test covering the failed
initialization path.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: f2984487-746f-446d-8a99-10a5a5806e3d

📥 Commits

Reviewing files that changed from the base of the PR and between 1b63224 and 0fe348a.

📒 Files selected for processing (5)
  • AGENTS.md
  • src/app/(main)/index.tsx
  • src/hooks/useAlarmById.ts
  • src/hooks/useCreateAlarmForm.ts
  • src/store/alarmStore.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • AGENTS.md
  • src/app/(main)/index.tsx
  • src/hooks/useCreateAlarmForm.ts

Comment thread src/hooks/useAlarmById.ts
Add an initError field to alarmStore, set it in the init failure path
and clear it on retry/success. useAlarmById now derives loading as
!loaded && !error and exposes error, so the edit screen renders an
error view with retry instead of hanging on "Loading alarm…".
@HoweiAY
HoweiAY merged commit fbdea62 into main Jul 31, 2026
1 check passed
@HoweiAY
HoweiAY deleted the feature/db branch July 31, 2026 11:01
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.

1 participant