Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

♻️ Remove explicit invalidate calls #1445

Merged
merged 2 commits into from
Nov 24, 2024
Merged

♻️ Remove explicit invalidate calls #1445

merged 2 commits into from
Nov 24, 2024

Conversation

lukevella
Copy link
Owner

@lukevella lukevella commented Nov 23, 2024

We don't need to invalidate queries explicitly since we invalidate all queries on any mutation

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced comment handling in the discussion component for improved responsiveness.
    • Streamlined mutation handling across various components, focusing on local state updates without unnecessary cache invalidation.
  • Bug Fixes

    • Adjusted translation logic for notifications toggle to improve formatting consistency.
  • Chores

    • Removed cache invalidation logic from multiple components to simplify state management after mutations.
    • Introduced an unstable_overrides property for enhanced mutation handling in the TRPC client.

Copy link

vercel bot commented Nov 23, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
app ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 24, 2024 3:05pm
1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
landing ⬜️ Skipped (Inspect) Nov 24, 2024 3:05pm

Copy link
Contributor

coderabbitai bot commented Nov 23, 2024

Walkthrough

The pull request introduces several modifications across various components in the application, primarily focusing on the removal of query invalidation logic associated with TRPC mutations. This change simplifies the handling of mutation success events across components, including account deletion, registration, login, and poll management. The overall structure of the components remains intact, with no alterations to user interface elements or form handling. The changes reflect a trend towards a more streamlined state management approach, reducing unnecessary network requests while maintaining core functionalities.

Changes

File Path Change Summary
apps/web/src/app/[locale]/(admin)/settings/profile/delete-account-dialog.tsx Removed trpcUtils and its associated invalidate() call from the onSuccess callback of the deleteAccount mutation.
apps/web/src/app/[locale]/(auth)/register/register-page.tsx Removed initialization of queryClient and its invalidate() call from the onSubmit handler of the VerifyCode component.
apps/web/src/app/[locale]/auth/login/login-page.tsx Removed trpcUtils and its invalidate() call from the onSuccess callback of the magicLinkFetch mutation.
apps/web/src/app/[locale]/poll/[urlId]/duplicate-dialog.tsx Removed queryClient and its invalidate() call from the onSuccess callback of the duplicate.mutate function.
apps/web/src/components/auth/auth-forms.tsx Minor adjustment in the URL string formatting in the verifyCode function; no functional changes.
apps/web/src/components/create-poll.tsx Removed queryClient and its invalidate() call from the onSuccess callback of the createPoll mutation.
apps/web/src/components/discussion/discussion.tsx Removed queryClient from NewCommentForm, altered comment handling logic, and updated deleteComment mutation's onMutate callback.
apps/web/src/components/participant-dropdown.tsx Removed queryClient and its invalidate() call from the onSuccess callback of the changeName mutation.
apps/web/src/components/poll/manage-poll.tsx Removed invalidate() calls from the onSuccess callbacks of resume, pause, and reopen mutations.
apps/web/src/components/poll/manage-poll/delete-poll-dialog.tsx Removed queryClient and its invalidate() call from the onSuccess callback of the deletePoll mutation.
apps/web/src/components/poll/manage-poll/finalize-poll-dialog.tsx Simplified mutation setup by removing the invalidate() call from the scheduleEvent mutation.
apps/web/src/components/poll/mutations.ts Removed invalidate() calls from useAddParticipantMutation, useDeleteParticipantMutation, and useUpdatePollMutation.
apps/web/src/components/poll/notifications-toggle.tsx Adjusted translation logic for notifications and removed invalidate() calls from watch and unwatch mutation success handlers.

Possibly related PRs

🐰 In the code we play,
Removing calls that sway,
Simplifying the flow,
Making it easier to grow.
With each change we cheer,
A clearer path is near!
🥕✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

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: 0

🧹 Outside diff range and nitpick comments (2)
apps/web/src/components/poll/notifications-toggle.tsx (1)

Line range hint 38-77: Well-implemented optimistic updates for mutations.

The mutation handlers implement optimistic updates correctly using setData, which is the recommended approach. This aligns well with the PR's objective of removing explicit invalidate calls, as the optimistic updates maintain UI consistency without requiring query invalidation.

The current implementation is a good example of proper state management in TRPC:

  1. Uses optimistic updates to maintain UI responsiveness
  2. Properly handles the cache updates without relying on invalidation
  3. Maintains data consistency across components
apps/web/src/components/poll/manage-poll/finalize-poll-dialog.tsx (1)

Line range hint 215-251: Consider improving mutation success handling.

While removing explicit invalidation is correct, consider these improvements for better UX:

  1. Add loading state handling to prevent dialog from closing before mutation completes
  2. Add error handling to show feedback on mutation failure
 const scheduleEvent = trpc.polls.book.useMutation();
+const scheduleEvent = trpc.polls.book.useMutation({
+  onError: (error) => {
+    // Show error toast/notification
+  },
+});

 // In onSubmit:
-scheduleEvent.mutate({
-  pollId: poll.id,
-  optionId: data.selectedOptionId,
-  notify: data.notify,
-});
-props.onOpenChange?.(false);
+scheduleEvent.mutate(
+  {
+    pollId: poll.id,
+    optionId: data.selectedOptionId,
+    notify: data.notify,
+  },
+  {
+    onSuccess: () => {
+      props.onOpenChange?.(false);
+    },
+  },
+);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 4b33765 and 1aab54d.

📒 Files selected for processing (13)
  • apps/web/src/app/[locale]/(admin)/settings/profile/delete-account-dialog.tsx (0 hunks)
  • apps/web/src/app/[locale]/(auth)/register/register-page.tsx (0 hunks)
  • apps/web/src/app/[locale]/auth/login/login-page.tsx (0 hunks)
  • apps/web/src/app/[locale]/poll/[urlId]/duplicate-dialog.tsx (0 hunks)
  • apps/web/src/components/auth/auth-forms.tsx (1 hunks)
  • apps/web/src/components/create-poll.tsx (0 hunks)
  • apps/web/src/components/discussion/discussion.tsx (0 hunks)
  • apps/web/src/components/participant-dropdown.tsx (0 hunks)
  • apps/web/src/components/poll/manage-poll.tsx (0 hunks)
  • apps/web/src/components/poll/manage-poll/delete-poll-dialog.tsx (0 hunks)
  • apps/web/src/components/poll/manage-poll/finalize-poll-dialog.tsx (1 hunks)
  • apps/web/src/components/poll/mutations.ts (0 hunks)
  • apps/web/src/components/poll/notifications-toggle.tsx (1 hunks)
💤 Files with no reviewable changes (10)
  • apps/web/src/app/[locale]/(admin)/settings/profile/delete-account-dialog.tsx
  • apps/web/src/app/[locale]/(auth)/register/register-page.tsx
  • apps/web/src/app/[locale]/auth/login/login-page.tsx
  • apps/web/src/app/[locale]/poll/[urlId]/duplicate-dialog.tsx
  • apps/web/src/components/create-poll.tsx
  • apps/web/src/components/discussion/discussion.tsx
  • apps/web/src/components/participant-dropdown.tsx
  • apps/web/src/components/poll/manage-poll.tsx
  • apps/web/src/components/poll/manage-poll/delete-poll-dialog.tsx
  • apps/web/src/components/poll/mutations.ts
✅ Files skipped from review due to trivial changes (1)
  • apps/web/src/components/auth/auth-forms.tsx
🔇 Additional comments (3)
apps/web/src/components/poll/notifications-toggle.tsx (1)

127-131: LGTM! Clean formatting of translation default values.

The formatting changes to the translation default values improve code consistency.

apps/web/src/components/poll/manage-poll/finalize-poll-dialog.tsx (2)

215-215: LGTM! Removal of explicit invalidation is correct.

The removal of explicit query invalidation aligns with the PR objective, as mutations automatically invalidate related queries.


215-215: Verify automatic invalidation coverage.

Let's verify that automatic invalidation properly updates all dependent queries.

✅ Verification successful

Let me gather more information with corrected file type flags.


Let me try with a different approach using more basic commands.


Let me check the router implementation and invalidation settings.


Let me check one more aspect focusing on the mutation implementation and its usage.


Based on the code analysis, I can now generate the final response:

Automatic invalidation is properly handled - no explicit invalidation needed

The polls.book mutation is used in a self-contained flow within the finalize-poll-dialog component. The mutation updates the poll's status to "finalized" and creates an event, which triggers tRPC's automatic cache invalidation. Related queries (polls.get, polls.getWatchers) will be automatically invalidated due to tRPC's built-in cache management.

  • The mutation changes the poll's status which automatically invalidates polls.get queries
  • The component properly handles the success case by closing the dialog
  • No other components directly depend on this mutation's result
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for components and queries that might be affected by this mutation

# Find components that might be watching the poll data
echo "Looking for components that depend on poll data..."
rg -l "polls\." --type tsx

# Find related query definitions
echo "Looking for related query definitions..."
rg "polls\.book" --type ts

Length of output: 408


Script:

#!/bin/bash
# Search for components using polls-related queries with correct file extension
echo "Components using polls queries:"
rg -l "polls\." --type typescript --type typescriptreact

# Look for query invalidation settings in the router
echo "\nRouter invalidation settings:"
rg -B5 -A5 "polls.book" --type typescript

# Check for other mutations that might affect poll data
echo "\nOther poll-related mutations:"
rg "polls\." --type typescript | grep -i "useMutation"

# Look for query definitions that might be affected
echo "\nPoll-related queries:"
rg "polls\." --type typescript | grep -i "useQuery"

Length of output: 623


Script:

#!/bin/bash
# Find all TypeScript/React files first
echo "Finding all TypeScript and React files:"
fd "\.(ts|tsx)$"

# Then use these files to search for polls-related queries
echo -e "\nSearching for poll-related queries and mutations:"
fd "\.(ts|tsx)$" --exec rg -l "polls\."

# Look specifically for the book mutation and surrounding context
echo -e "\nSearching for book mutation context:"
fd "\.(ts|tsx)$" --exec rg -B5 -A5 "polls\.book" {}

# Search for tRPC router definitions
echo -e "\nSearching for tRPC router definitions:"
fd "router\.(ts|tsx)$" --exec rg -l "polls"

Length of output: 19184


Script:

#!/bin/bash
# Check the polls router implementation for invalidation settings
echo "Checking polls router implementation:"
rg -B10 -A10 "book.*=.*procedure" apps/web/src/trpc/routers/polls.ts

# Look for query definitions that might be affected by this mutation
echo -e "\nChecking query definitions in polls router:"
rg "useQuery.*polls\." apps/web/src/components/poll/

# Check for any invalidation calls in the finalize dialog
echo -e "\nChecking finalize dialog implementation:"
rg -A10 "polls\.book\.useMutation" apps/web/src/components/poll/manage-poll/finalize-poll-dialog.tsx

Length of output: 842


Script:

#!/bin/bash
# Check the entire finalize dialog implementation for mutation usage
echo "Checking complete finalize dialog implementation:"
cat apps/web/src/components/poll/manage-poll/finalize-poll-dialog.tsx

# Check the polls router for book procedure implementation
echo -e "\nChecking polls router for book procedure:"
cat apps/web/src/trpc/routers/polls.ts

# Look for any related queries that might need invalidation
echo -e "\nChecking for related queries:"
rg "polls\.(get|by|find)" apps/web/src/components/poll/

Length of output: 33622

@vercel vercel bot temporarily deployed to Preview – landing November 24, 2024 15:01 Inactive
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

🧹 Outside diff range and nitpick comments (1)
apps/web/src/trpc/client.ts (1)

10-10: Consider the implications of using unstable API features

The unstable_ prefix indicates this is an experimental API that may change in future versions. Consider:

  1. Documenting this decision
  2. Adding a version pin for tRPC
  3. Creating a migration plan for when this API stabilizes
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1aab54d and 5503470.

📒 Files selected for processing (2)
  • apps/web/src/components/discussion/discussion.tsx (0 hunks)
  • apps/web/src/trpc/client.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • apps/web/src/components/discussion/discussion.tsx
🔇 Additional comments (1)
apps/web/src/trpc/client.ts (1)

13-14: 🛠️ Refactor suggestion

Verify the performance impact of blanket query invalidation

Invalidating all queries after every mutation could be inefficient if the application has many queries that are unrelated to the mutation.

Let's analyze the query usage in the codebase:

Consider implementing more selective invalidation based on the mutation type:

  async onSuccess(opts) {
    await opts.originalFn();
-   await opts.queryClient.invalidateQueries();
+   // Extract mutation path from opts and invalidate related queries only
+   const mutationPath = opts.mutation.options.mutationKey[0];
+   await opts.queryClient.invalidateQueries({ queryKey: [mutationPath] });
  },
✅ Verification successful

Blanket query invalidation is acceptable in this codebase

The codebase has minimal query usage with only one query for authentication providers that is explicitly set with Infinity for both cacheTime and staleTime. This means the blanket invalidation won't cause unnecessary re-fetches since:

  • The providers query won't be affected due to its infinite stale time
  • There's only one mutation related to authentication
  • The invalidation appears in auth-related contexts where a full cache clear is appropriate
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Analyze query usage to assess the impact of blanket invalidation

# Find all tRPC query definitions
echo "=== Query Definitions ==="
ast-grep --pattern 'useQuery($$$)' 

# Find all tRPC mutation definitions
echo "=== Mutation Definitions ==="
ast-grep --pattern 'useMutation($$$)'

# Look for existing selective invalidation patterns
echo "=== Existing Invalidation Patterns ==="
rg -A 2 'invalidateQueries\(' 

Length of output: 2764

@lukevella lukevella merged commit a34aa8c into main Nov 24, 2024
9 checks passed
@lukevella lukevella deleted the remove-invalidate branch November 24, 2024 15:08
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