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

Feat: add optimistic updates #8

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/components/Comment.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ const CommentData: FC<CommentDataProps> = ({ comment }) => {
addReaction: useAddReaction(),
removeReaction: useRemoveReaction(),
updateComment: useUpdateComment(),
deleteComment: useDeleteComment(),
deleteComment: useDeleteComment(comment),
};
const { isAuthenticated, runIfAuthenticated, auth } = useAuthUtils();

Expand Down
42 changes: 42 additions & 0 deletions src/hooks/useAddComment.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { useMutation, useQueryClient } from 'react-query';
import { Comment } from '../api';
import { useSupabaseClient } from '../components/CommentsProvider';
import { randomString } from '../utils';
import useApi from './useApi';

interface UseAddCommentPayload {
Expand All @@ -11,6 +14,7 @@ interface UseAddCommentPayload {
const useAddComment = () => {
const queryClient = useQueryClient();
const api = useApi();
const supabaseClient = useSupabaseClient();

return useMutation(
({ comment, topic, parentId, mentionedUserIds }: UseAddCommentPayload) => {
Expand All @@ -22,6 +26,44 @@ const useAddComment = () => {
});
},
{
onMutate: (payload) => {
queryClient.setQueryData<Comment[]>(
['comments', { topic: payload.topic, parentId: payload.parentId }],
(comments = []) => {
const user = supabaseClient.auth.user();

if (!user) return comments;

const userMetadata = user.user_metadata;

const name =
userMetadata.name ||
userMetadata.full_name ||
userMetadata.user_name;
const avatar = userMetadata.avatar || userMetadata.avatar_url;

comments.push({
comment: payload.comment,
topic: payload.topic,
parent_id: payload.parentId,
user_id: user?.id,
mentioned_user_ids: payload.mentionedUserIds,
created_at: new Date().toUTCString(),
// Fake id, use random string to make sure the comment is unique
id: randomString(),
replies_count: 0,
user: {
avatar,
name,
id: user.id,
},
reactions_metadata: [],
});

return comments;
}
);
},
onSuccess: (data, params) => {
queryClient.invalidateQueries([
'comments',
Expand Down
53 changes: 49 additions & 4 deletions src/hooks/useAddReaction.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { Item } from '@supabase/ui/dist/cjs/components/Accordion/Accordion';
import { useMutation, useQueryClient } from 'react-query';
import { Comment, CommentReactionMetadata } from '../api';
import { Comment, CommentReaction, CommentReactionMetadata } from '../api';
import { useSupabaseClient } from '../components/CommentsProvider';
import { randomString } from '../utils';
import useApi from './useApi';

interface UseAddReactionPayload {
Expand Down Expand Up @@ -46,6 +48,7 @@ const addOrIncrement = (reactionType: string, comment: Comment): Comment => {
const useAddReaction = () => {
const api = useApi();
const queryClient = useQueryClient();
const supabaseClient = useSupabaseClient();

return useMutation(
(payload: UseAddReactionPayload) => {
Expand All @@ -55,12 +58,54 @@ const useAddReaction = () => {
});
},
{
onSuccess: (data, params) => {
onMutate: (payload) => {
// Manually patch the comment while it refetches
queryClient.setQueryData(
['comments', params.commentId],
(prev: Comment) => addOrIncrement(params.reactionType, prev)
['comments', payload.commentId],
(prev: Comment) => addOrIncrement(payload.reactionType, prev)
);

queryClient.setQueryData<CommentReaction[]>(
[
'comment-reactions',
{
commentId: payload.commentId,
reactionType: payload.reactionType,
},
],
(reactions = []) => {
const user = supabaseClient.auth.user();

if (!user) return reactions;

const userMetadata = user.user_metadata;

const name =
userMetadata.name ||
userMetadata.full_name ||
userMetadata.user_name;
const avatar = userMetadata.avatar || userMetadata.avatar_url;

const newReactions = reactions?.length ? [...reactions] : [];

newReactions.push({
comment_id: payload.commentId,
created_at: new Date().toUTCString(),
id: randomString(),
reaction_type: payload.reactionType,
user: {
avatar,
name,
id: user?.id,
},
user_id: user.id,
});

return newReactions;
}
);
},
onSuccess: (data, params) => {
queryClient.invalidateQueries(['comments', params.commentId]);
queryClient.invalidateQueries([
'comment-reactions',
Expand Down
9 changes: 8 additions & 1 deletion src/hooks/useDeleteComment.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { useMutation, useQueryClient } from 'react-query';
import { Comment } from '../api';
import useApi from './useApi';

interface UseDeleteCommentPayload {
id: string;
}

const useDeleteComment = () => {
const useDeleteComment = (comment: Comment) => {
const queryClient = useQueryClient();
const api = useApi();

Expand All @@ -14,6 +15,12 @@ const useDeleteComment = () => {
return api.deleteComment(id);
},
{
onMutate: ({ id }) => {
queryClient.setQueryData<Comment[]>(
['comments', { topic: comment.topic, parentId: comment.parent_id }],
(comments = []) => comments.filter((comment) => comment.id !== id)
);
},
onSuccess: (data) => {
queryClient.invalidateQueries([
'comments',
Expand Down
35 changes: 31 additions & 4 deletions src/hooks/useRemoveReaction.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useMutation, useQueryClient } from 'react-query';
import { Comment } from '../api';
import { Comment, CommentReaction } from '../api';
import { useSupabaseClient } from '../components/CommentsProvider';
import useApi from './useApi';

interface UseRemoveReactionPayload {
Expand Down Expand Up @@ -35,6 +36,7 @@ const removeOrDecrement = (reactionType: string, comment: Comment): Comment => {
const useRemoveReaction = () => {
const api = useApi();
const queryClient = useQueryClient();
const supabaseClient = useSupabaseClient();

return useMutation(
(payload: UseRemoveReactionPayload) => {
Expand All @@ -44,12 +46,37 @@ const useRemoveReaction = () => {
});
},
{
onSuccess: (data, params) => {
onMutate: (payload) => {
// Manually patch the comment while it refetches
queryClient.setQueryData(
['comments', params.commentId],
(prev: Comment) => removeOrDecrement(params.reactionType, prev)
['comments', payload.commentId],
(prev: Comment) => removeOrDecrement(payload.reactionType, prev)
);

queryClient.setQueryData<CommentReaction[]>(
[
'comment-reactions',
{
commentId: payload.commentId,
reactionType: payload.reactionType,
},
],
(reactions) => {
if (!reactions?.length) return [];

const user = supabaseClient.auth.user();

if (!user) return reactions;

return reactions.filter(
(reaction) =>
reaction.user_id !== user.id &&
reaction.reaction_type !== payload.reactionType
);
}
);
},
onSuccess: (data, params) => {
queryClient.invalidateQueries(['comments', params.commentId]);
queryClient.invalidateQueries([
'comment-reactions',
Expand Down
13 changes: 13 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,18 @@ export const getMentionedUserIds = (doc: string): string[] => {
return userIds;
};

export const randomString = (length = 8) => {
const chars =
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

let result = '';

for (let i = length; i > 0; --i) {
result += chars[Math.floor(Math.random() * chars.length)];
}

return result;
};

export const timeout = (ms: number) =>
new Promise((resolve) => setTimeout(resolve, ms));