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

fix: fixed problem with update bookmarks #879

Closed
wants to merge 3 commits into from

Conversation

Maczi01
Copy link
Contributor

@Maczi01 Maczi01 commented Apr 2, 2024

✨ Codu Pull Request 💻

Codu Logo

Pull Request details

Fixed problems with update bookmarks - after click icon, article will be added to bookmarks + toast "Bookmark updated"

Any Breaking changes

Important. I am not sure it is most efficient solution.

In onSuccess I am invalidating query, with queryClient.invalidateQueries();
Imo problem is with invalidate all queries, not particular one. I tried with:
queryClient.invalidateQueries([myBookmarks), but it doesn't work

Associated Screenshots

image

Summary by CodeRabbit

  • New Features
    • Introduced success notifications for bookmark updates in article previews.
    • Refactored bookmark mutation handling to improve user experience.

@Maczi01 Maczi01 requested a review from a team as a code owner April 2, 2024 21:30
Copy link

vercel bot commented Apr 2, 2024

@Maczi01 is attempting to deploy a commit to the Codú Team on Vercel.

A member of the Team first needs to authorize it.

Copy link
Contributor

coderabbitai bot commented Apr 2, 2024

Walkthrough

The update involves enhancing the ArticlePreview component with new functionalities to improve user experience. It now uses useQueryClient for managing query states and toast for displaying success messages, providing immediate feedback to users during bookmark updates.

Changes

File Summary
components/.../ArticlePreview.tsx Added imports for useQueryClient and toast. Refactored bookmark mutation handling with loading state and success toast. Added disabled attribute to bookmark button.

Poem

In a codebase, not so vast,
A rabbit hopped in, quite fast.
"Let's add some magic," it said with glee,
To make bookmarks as lively as can be.
🌟 With a toast that pops, and queries that dance,
Now every update gets its chance.
🐰 "With each change, we grow," whispers the rabbit,
"In this digital burrow, we weave our habit."


Recent Review Details

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 05bcb79 and 6b492b1.
Files selected for processing (1)
  • components/ArticlePreview/ArticlePreview.tsx (3 hunks)
Files skipped from review as they are similar to previous changes (1)
  • components/ArticlePreview/ArticlePreview.tsx

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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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.

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 as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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: 1

Review Status

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between ecb2958 and dcc88cc.
Files selected for processing (1)
  • components/ArticlePreview/ArticlePreview.tsx (2 hunks)
Additional comments not posted (2)
components/ArticlePreview/ArticlePreview.tsx (2)

14-15: The import statements for useQueryClient and toast are correctly added and necessary for the bookmark update functionality and displaying success messages.


63-63: The initialization of queryClient using useQueryClient is correctly implemented for invalidating queries after bookmark updates.

Comment on lines 70 to 72
async onSuccess() {
await queryClient.invalidateQueries();
toast.success("Bookmarks updated!");
Copy link
Contributor

Choose a reason for hiding this comment

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

Refine the query invalidation to target specific queries related to bookmarks for improved efficiency.

- await queryClient.invalidateQueries();
+ await queryClient.invalidateQueries(['myBookmarks']);

If targeting specific queries does not work as expected, ensure that the query keys used in invalidateQueries match exactly those used in your query definitions. Also, verify that the data structure returned by the queries is consistent.


Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
async onSuccess() {
await queryClient.invalidateQueries();
toast.success("Bookmarks updated!");
async onSuccess() {
await queryClient.invalidateQueries(['myBookmarks']);
toast.success("Bookmarks updated!");

Copy link
Contributor

@NiallJoeMaher NiallJoeMaher left a comment

Choose a reason for hiding this comment

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

Thanks for this! ❤️

Aha, the problem here is we need an optimistic update. Basically, in local development it's hard to test because everything happens fast. But it's so the bookmark instantly is filled or unfilled when bookmarking or unmarking. In production you'll notice a half second delay which could cause the user to hit it multiple times. This will behave the exact same except we have a toast now too.

So the solution doesn't need a notification but it does need to look like the user has instantly bookmarked something (and then only alert them if something went wrong which should be rare).

@Maczi01
Copy link
Contributor Author

Maczi01 commented Apr 5, 2024

Whooo, optimistic update can be perfect here.
I am struggling with implement it, some query keys problem:

https://tanstack.com/query/v4/docs/framework/react/guides/optimistic-updates

Maybe we can change approach a littie bit and use disabled property on button? Something like:
<button disabled={isLoading},

I can get isLoading from useMutation.

@NiallJoeMaher
Copy link
Contributor

Whooo, optimistic update can be perfect here. I am struggling with implement it, some query keys problem:

https://tanstack.com/query/v4/docs/framework/react/guides/optimistic-updates

Maybe we can change approach a littie bit and use disabled property on button? Something like: <button disabled={isLoading},

I can get isLoading from useMutation.

Sorry I'm slow getting back to you. Yeah something like that might be good! I'll also take a look and see what options there is

@Maczi01
Copy link
Contributor Author

Maczi01 commented Apr 19, 2024

@NiallJoeMaher can you check it now? button will be disable during action, it prevent sending another request. Should be helpful :-) If not, we can talk about better solution

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

Comment on lines +63 to +76
const queryClient = useQueryClient();

const {
mutate: bookmark,
status: bookmarkStatus,
isLoading,
} = api.post.bookmark.useMutation({
onSettled() {
setIsBookmarked((isBookmarked) => !isBookmarked);
},
async onSuccess() {
await queryClient.invalidateQueries();
toast.success("Bookmarks updated!");
},
Copy link
Contributor

Choose a reason for hiding this comment

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

Refine the query invalidation to target specific queries related to bookmarks for improved efficiency.

- await queryClient.invalidateQueries();
+ await queryClient.invalidateQueries(['bookmarks']);

If targeting specific queries does not work as expected, ensure that the query keys used in invalidateQueries match exactly those used in your query definitions. Also, verify that the data structure returned by the queries is consistent.


Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
const queryClient = useQueryClient();
const {
mutate: bookmark,
status: bookmarkStatus,
isLoading,
} = api.post.bookmark.useMutation({
onSettled() {
setIsBookmarked((isBookmarked) => !isBookmarked);
},
async onSuccess() {
await queryClient.invalidateQueries();
toast.success("Bookmarks updated!");
},
const queryClient = useQueryClient();
const {
mutate: bookmark,
status: bookmarkStatus,
isLoading,
} = api.post.bookmark.useMutation({
onSettled() {
setIsBookmarked((isBookmarked) => !isBookmarked);
},
async onSuccess() {
await queryClient.invalidateQueries(['bookmarks']);
toast.success("Bookmarks updated!");
},

Copy link
Contributor

@NiallJoeMaher NiallJoeMaher left a comment

Choose a reason for hiding this comment

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

This is awesome, and would work very well. I'm going to suggest something more opinionated because I like how it looks 🙈

I was looking at the docs for "optimistic updates" and found this: https://tanstack.com/query/latest/docs/framework/react/guides/mutations#mutation-side-effects

  onMutate: variables => {
    // A mutation is about to happen!
    // We can update right away
    // Return a context containing data to use when for example rolling back
    return { id: 1 }
  },
  onError: (error, variables, context) => {
    // An error happened!
    console.log(`rolling back optimistic update with id ${context.id}`)
  },

I'm not sure how the logic would work inside it but basically, on mutate, update the UI right away (as if the bookmark worked instantly) and then only on error roll back and present an error toast. I think a toast pop up for every bookmark success might get annoying especially on small screens.

Example:
https://tanstack.com/query/v3/docs/framework/react/examples/optimistic-updates-typescript

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.

None yet

2 participants