Skip to content

feat(useAuth): add refreshOnMount option to sync user data#13

Open
emilianocalzada wants to merge 1 commit into
KevinBonnoron:mainfrom
emilianocalzada:fix/refresh-user-on-mount
Open

feat(useAuth): add refreshOnMount option to sync user data#13
emilianocalzada wants to merge 1 commit into
KevinBonnoron:mainfrom
emilianocalzada:fix/refresh-user-on-mount

Conversation

@emilianocalzada
Copy link
Copy Markdown

@emilianocalzada emilianocalzada commented Nov 26, 2025

Fixes issue where useAuth returns stale user data after screen navigation. When refreshOnMount is true, the hook calls authRefresh() on mount to fetch the latest user data from the server.

Changes Made:

1: src/types/useAuth.type.ts - Added the refreshOnMount option to UseAuthOptions:

export interface UseAuthOptions {
  collectionName?: string;
  realtime?: boolean;
  refreshOnMount?: boolean;  // New option
}

2: src/hooks/useAuth.ts - Added a useEffect that calls authRefresh() on mount when refreshOnMount: true:

useEffect(() => {
  if (!refreshOnMount || !pb.authStore.isValid) {
    return;
  }

  let cancelled = false;

  const refresh = async () => {
    try {
      const authData = await recordService.authRefresh<User>();
      if (!cancelled) {
        setUser(authData.record);
      }
    } catch {
      // silently ignore refresh errors on mount
    }
  };

  refresh();

  return () => {
    cancelled = true;
  };
}, [refreshOnMount, pb.authStore.isValid, recordService]);

3: tests/hooks/useAuth.test.tsx - Added 4 new tests for the refreshOnMount feature.

Summary by CodeRabbit

  • New Features
    • Introduced optional automatic user data refresh on component mount. When enabled, the application refreshes your user information from the server immediately upon component initialization if you're already logged in. This ensures your session stays current without manual intervention. The feature is disabled by default.

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

Fixes issue where useAuth returns stale user data after screen navigation.
When refreshOnMount is true, the hook calls authRefresh() on mount to
fetch the latest user data from the server.
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Nov 26, 2025

Walkthrough

A new refreshOnMount option is added to the useAuth hook with a default value of false. When enabled and the user is authenticated, the hook automatically refreshes user data from the server on component mount, silently ignoring any refresh errors.

Changes

Cohort / File(s) Summary
refreshOnMount Option Implementation
src/types/useAuth.type.ts, src/hooks/useAuth.ts, tests/hooks/useAuth.test.tsx
Adds optional refreshOnMount boolean field to UseAuthOptions interface. Implements new mount effect in useAuth hook that calls recordService.authRefresh when enabled and authenticated. Introduces four test cases validating refresh behavior on mount, default behavior, unauthenticated state, and error handling.

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 clearly and specifically describes the main change: adding a refreshOnMount option to the useAuth hook to sync user data.
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

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1068cc6 and 5854ba8.

📒 Files selected for processing (3)
  • src/hooks/useAuth.ts (2 hunks)
  • src/types/useAuth.type.ts (1 hunks)
  • tests/hooks/useAuth.test.tsx (1 hunks)
🧰 Additional context used
🧠 Learnings (12)
📓 Common learnings
Learnt from: CR
Repo: KevinBonnoron/pocketbase-react-hooks PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-10-18T12:22:11.415Z
Learning: Applies to src/hooks/useAuth.{ts,tsx} : useAuth must listen to pb.authStore.onChange(), provide signIn.email(), signIn.social(), signUp.email(), and signOut(), and expose the authenticated user via pb.authStore.model
📚 Learning: 2025-10-18T12:22:11.415Z
Learnt from: CR
Repo: KevinBonnoron/pocketbase-react-hooks PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-10-18T12:22:11.415Z
Learning: Applies to src/hooks/useAuth.{ts,tsx} : useAuth must listen to pb.authStore.onChange(), provide signIn.email(), signIn.social(), signUp.email(), and signOut(), and expose the authenticated user via pb.authStore.model

Applied to files:

  • src/types/useAuth.type.ts
  • src/hooks/useAuth.ts
  • tests/hooks/useAuth.test.tsx
📚 Learning: 2025-10-18T12:22:42.070Z
Learnt from: CR
Repo: KevinBonnoron/pocketbase-react-hooks PR: 0
File: .cursorrules:0-0
Timestamp: 2025-10-18T12:22:42.070Z
Learning: Applies to src/hooks/**/*.{ts,tsx} : Use signIn/signOut for auth hooks (not login/logout) and signUp (not register)

Applied to files:

  • src/hooks/useAuth.ts
📚 Learning: 2025-10-18T12:22:11.415Z
Learnt from: CR
Repo: KevinBonnoron/pocketbase-react-hooks PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-10-18T12:22:11.415Z
Learning: Applies to src/hooks/**/*.{ts,tsx} : Provide generic type parameters for records in hooks, e.g., useCollection<Post>() and useAuth<User>()

Applied to files:

  • src/hooks/useAuth.ts
📚 Learning: 2025-10-18T12:22:11.415Z
Learnt from: CR
Repo: KevinBonnoron/pocketbase-react-hooks PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-10-18T12:22:11.415Z
Learning: Applies to src/hooks/useCollection.{ts,tsx} : useCollection should fetch with getFullList() or getList() based on fetchAll, handle real-time create/update/delete, and re-sort as needed

Applied to files:

  • src/hooks/useAuth.ts
📚 Learning: 2025-10-18T12:22:11.415Z
Learnt from: CR
Repo: KevinBonnoron/pocketbase-react-hooks PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-10-18T12:22:11.415Z
Learning: Applies to src/hooks/{useCollection,useRecord}.{ts,tsx} : useCollection and useRecord must support a transformers option (array of RecordTransformer<T>) applied sequentially (reduce) to initial fetch and real-time updates; default include dateTransformer()

Applied to files:

  • src/hooks/useAuth.ts
📚 Learning: 2025-10-18T12:22:11.415Z
Learnt from: CR
Repo: KevinBonnoron/pocketbase-react-hooks PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-10-18T12:22:11.415Z
Learning: Applies to src/hooks/**/*.{ts,tsx} : Hooks must set up PocketBase real-time subscriptions via pb.collection().subscribe() and clean up subscriptions in useEffect

Applied to files:

  • src/hooks/useAuth.ts
📚 Learning: 2025-10-18T12:22:11.415Z
Learnt from: CR
Repo: KevinBonnoron/pocketbase-react-hooks PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-10-18T12:22:11.415Z
Learning: Applies to tests/hooks/**/*.{test,spec}.{ts,tsx} : Use renderHook from testing-library/react and wrap hooks with PocketBaseProvider using a mocked client

Applied to files:

  • tests/hooks/useAuth.test.tsx
📚 Learning: 2025-10-18T12:22:42.070Z
Learnt from: CR
Repo: KevinBonnoron/pocketbase-react-hooks PR: 0
File: .cursorrules:0-0
Timestamp: 2025-10-18T12:22:42.070Z
Learning: Applies to tests/**/*.{ts,tsx} : Mock PocketBase methods comprehensively in tests

Applied to files:

  • tests/hooks/useAuth.test.tsx
📚 Learning: 2025-10-18T12:22:11.415Z
Learnt from: CR
Repo: KevinBonnoron/pocketbase-react-hooks PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-10-18T12:22:11.415Z
Learning: Applies to tests/hooks/**/*.{test,spec}.{ts,tsx} : Mock PocketBase client methods with Vitest vi.fn() and test loading, success, and error states

Applied to files:

  • tests/hooks/useAuth.test.tsx
📚 Learning: 2025-10-18T12:22:42.070Z
Learnt from: CR
Repo: KevinBonnoron/pocketbase-react-hooks PR: 0
File: .cursorrules:0-0
Timestamp: 2025-10-18T12:22:42.070Z
Learning: Applies to tests/**/*.{ts,tsx} : Test all hook states: loading, success, error

Applied to files:

  • tests/hooks/useAuth.test.tsx
📚 Learning: 2025-10-18T12:22:11.415Z
Learnt from: CR
Repo: KevinBonnoron/pocketbase-react-hooks PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-10-18T12:22:11.415Z
Learning: Applies to tests/hooks/**/*.{test,spec}.{ts,tsx} : Verify real-time subscription setup and cleanup in tests

Applied to files:

  • tests/hooks/useAuth.test.tsx
🧬 Code graph analysis (2)
src/hooks/useAuth.ts (2)
src/index.ts (2)
  • useAuth (5-5)
  • UseAuthResult (11-11)
src/types/useAuth.type.ts (2)
  • UseAuthOptions (7-26)
  • UseAuthResult (33-133)
tests/hooks/useAuth.test.tsx (1)
src/hooks/useAuth.ts (1)
  • useAuth (33-256)
🔇 Additional comments (4)
src/types/useAuth.type.ts (1)

17-25: LGTM!

The new refreshOnMount option is well-documented with clear JSDoc comments explaining the default behavior and use case. The optional nature with false default maintains backward compatibility.

tests/hooks/useAuth.test.tsx (1)

211-308: Good test coverage for the refreshOnMount feature.

The test suite covers the essential scenarios: refresh on mount when enabled, no refresh when disabled (default), no refresh when unauthenticated, and silent error handling. Tests follow existing patterns with proper mocking.

src/hooks/useAuth.ts (2)

33-33: LGTM!

Clean destructuring with appropriate default value maintains backward compatibility.


46-69: Solid implementation with proper cancellation handling.

The effect correctly:

  • Guards against unnecessary execution when refreshOnMount is false or auth is invalid
  • Uses a cancellation flag to prevent state updates after unmount
  • Silently ignores refresh errors as intended

One consideration: The dependency on pb.authStore.isValid means if a user signs in (isValid changes from false to true) while refreshOnMount is true, this effect will re-run and trigger a refresh. This is likely harmless since login already updates the user state, but it results in an extra network call. If this becomes a concern, you could track whether the initial mount refresh has already occurred.

Tip

📝 Customizable high-level summaries are now available in beta!

You can now customize how CodeRabbit generates the high-level summary in your pull requests — including its content, structure, tone, and formatting.

  • Provide your own instructions using the high_level_summary_instructions setting.
  • Format the summary however you like (bullet lists, tables, multi-section layouts, contributor stats, etc.).
  • Use high_level_summary_in_walkthrough to move the summary from the description to the walkthrough section.

Example instruction:

"Divide the high-level summary into five sections:

  1. 📝 Description — Summarize the main change in 50–60 words, explaining what was done.
  2. 📓 References — List relevant issues, discussions, documentation, or related PRs.
  3. 📦 Dependencies & Requirements — Mention any new/updated dependencies, environment variable changes, or configuration updates.
  4. 📊 Contributor Summary — Include a Markdown table showing contributions:
    | Contributor | Lines Added | Lines Removed | Files Changed |
  5. ✔️ Additional Notes — Add any extra reviewer context.
    Keep each section concise (under 200 words) and use bullet or numbered lists for clarity."

Note: This feature is currently in beta for Pro-tier users, and pricing will be announced later.


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

@KevinBonnoron
Copy link
Copy Markdown
Owner

Hey @emilianocalzada,

Thanks for your contribution.

Don't have much time these days sorry. Will try to take a look at it this week-end.

Regards

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