Skip to content

Commit

Permalink
Reset cache on comment mutation actions
Browse files Browse the repository at this point in the history
  • Loading branch information
mzparacha committed Dec 26, 2024
1 parent 7230a85 commit 308f1db
Show file tree
Hide file tree
Showing 8 changed files with 103 additions and 206 deletions.
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import { toCanvasSignedDataApiArgs } from '@hicommonwealth/shared';
import { useQueryClient } from '@tanstack/react-query';
import { signComment } from 'controllers/server/sessions';
import Comment from 'models/Comment';
import { ApiEndpoints } from 'state/api/config';
import useUserOnboardingSliderMutationStore from 'state/ui/userTrainingCards';
import { UserTrainingCardTypes } from 'views/components/UserTrainingSlider/types';
import { trpc } from '../../../utils/trpcClient';
Expand Down Expand Up @@ -48,15 +46,11 @@ const useCreateCommentMutation = ({
communityId,
threadId,
existingNumberOfComments = 0,
}: Partial<CreateCommentProps>) => {
const queryClient = useQueryClient();
// TODO: fix cache updates
const comments = [];
// const { data: comments } = useFetchCommentsQuery({
// communityId: communityId!,
// threadId: threadId!,
// });

}: Pick<
CreateCommentProps,
'communityId' | 'threadId' | 'existingNumberOfComments'
>) => {
const utils = trpc.useUtils();
const user = useUserStore();

const { markTrainingActionAsComplete } =
Expand All @@ -69,15 +63,12 @@ const useCreateCommentMutation = ({
// @ts-expect-error StrictNullChecks
const comment = new Comment(newComment);

// update fetch comments query state
const key = [ApiEndpoints.FETCH_COMMENTS, communityId, threadId];
queryClient.cancelQueries({ queryKey: key });
queryClient.setQueryData(key, () => {
return [...comments, comment];
});
// TODO: #8015 - make a generic util to apply cache
// updates for comments in all possible key combinations
// present in cache.
utils.comment.getComments.invalidate();

// @ts-expect-error StrictNullChecks
updateThreadInAllCaches(communityId, threadId, {
updateThreadInAllCaches(communityId || '', threadId, {
numberOfComments: existingNumberOfComments + 1,
});

Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { toCanvasSignedDataApiArgs } from '@hicommonwealth/shared';
import { useQueryClient } from '@tanstack/react-query';
import { AxiosError } from 'axios';
import { notifyError } from 'client/scripts/controllers/app/notifications';
import { trpc } from 'client/scripts/utils/trpcClient';
import { notifyError } from 'controllers/app/notifications';
import { signCommentReaction } from 'controllers/server/sessions';
import useUserOnboardingSliderMutationStore from 'state/ui/userTrainingCards';
import { trpc } from 'utils/trpcClient';
import { UserTrainingCardTypes } from 'views/components/UserTrainingSlider/types';
import { useAuthModalStore } from '../../ui/modals';
import useUserStore, { userStore } from '../../ui/user';
Expand Down Expand Up @@ -42,20 +41,8 @@ export const buildCreateCommentReactionInput = async ({
};
};

const useCreateCommentReactionMutation = ({
threadId,
commentId,
communityId,
}: Partial<CreateReactionProps>) => {
const queryClient = useQueryClient();
// TODO: fix cache updates
const comments = [];
// const { data: comments } = useFetchCommentsQuery({
// // @ts-expect-error StrictNullChecks
// communityId,
// // @ts-expect-error StrictNullChecks
// threadId,
// });
const useCreateCommentReactionMutation = () => {
const utils = trpc.useUtils();
const user = useUserStore();

const { markTrainingActionAsComplete } =
Expand All @@ -65,19 +52,10 @@ const useCreateCommentReactionMutation = ({

return trpc.comment.createCommentReaction.useMutation({
onSuccess: (newReaction) => {
// update fetch comments query state
// const key = [ApiEndpoints.FETCH_COMMENTS, communityId, threadId];
// queryClient.cancelQueries({ queryKey: key });
// queryClient.setQueryData(key, () => {
// const tempComments = [...comments];
// const commentToUpdate = tempComments.find((x) => x.id === commentId);
// newReaction.Address!.User = {
// profile: commentToUpdate.profile,
// };
// // @ts-expect-error StrictNullChecks
// commentToUpdate.reactions.push(new Reaction(newReaction));
// return tempComments;
// });
// TODO: #8015 - make a generic util to apply cache
// updates for comments in all possible key combinations
// present in cache.
utils.comment.getComments.invalidate();

const userId = user.addresses?.[0]?.profile?.userId;
userId &&
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { useQueryClient } from '@tanstack/react-query';
import { trpc } from 'client/scripts/utils/trpcClient';
import Comment from 'models/Comment';
import { IUniqueId } from 'models/interfaces';
import { trpc } from 'utils/trpcClient';
import { useAuthModalStore } from '../../ui/modals';
import { updateThreadInAllCaches } from '../threads/helpers/cache';

interface UseDeleteCommentMutationProps {
communityId: string;
Expand All @@ -13,59 +15,42 @@ const useDeleteCommentMutation = ({
threadId,
existingNumberOfComments,
}: UseDeleteCommentMutationProps) => {
const queryClient = useQueryClient();
// TODO: fix cache updates
const comments = [];
// const { data: comments } = useFetchCommentsQuery({
// communityId,
// threadId,
// });
const utils = trpc.useUtils();

const { checkForSessionKeyRevalidationErrors } = useAuthModalStore();

return trpc.comment.deleteComment.useMutation({
// TODO: need to properly display deleted comment tree in <CommentTree/>
onSuccess: async (response) => {
// Important: we render comments in a tree, if the deleted comment is a
// leaf node, remove it, but if it has replies, then preserve it with
// [deleted] msg.
// const softDeleted = {
// id: response.comment_id,
// deleted: true,
// text: '[deleted]',
// versionHistory: [],
// canvas_signed_data: response.canvas_signed_data,
// canvas_msg_id: response.canvas_msg_id,
// };
// // find the existing comment index
// const foundCommentIndex = comments.findIndex(
// (x) => x.id === softDeleted.id,
// );
// if (foundCommentIndex > -1) {
// const softDeletedComment = Object.assign(
// { ...comments[foundCommentIndex] },
// { ...softDeleted },
// );
// // update fetch comments query state
// const key = [ApiEndpoints.FETCH_COMMENTS, communityId, threadId];
// queryClient.cancelQueries({ queryKey: key });
// queryClient.setQueryData(key, () => {
// const updatedComments = [...(comments || [])];
// updatedComments[foundCommentIndex] = softDeletedComment;
// return [...updatedComments];
// });
// }
// updateThreadInAllCaches(communityId, threadId, {
// numberOfComments: existingNumberOfComments - 1 || 0,
// });
// updateThreadInAllCaches(
// communityId,
// threadId,
// {
// recentComments: [{ id: softDeleted.id }] as Comment<IUniqueId>[],
// },
// 'removeFromExisting',
// );
// return softDeleted;
const softDeleted = {
id: response.comment_id,
deleted: true,
text: '[deleted]',
versionHistory: [],
canvas_signed_data: response.canvas_signed_data,
canvas_msg_id: response.canvas_msg_id,
};

// TODO: #8015 - make a generic util to apply cache
// updates for comments in all possible key combinations
// present in cache.
utils.comment.getComments.invalidate();

updateThreadInAllCaches(communityId, threadId, {
numberOfComments: existingNumberOfComments - 1 || 0,
});
updateThreadInAllCaches(
communityId,
threadId,
{
recentComments: [{ id: softDeleted.id }] as Comment<IUniqueId>[],
},
'removeFromExisting',
);
return softDeleted;
},
onError: (error) => checkForSessionKeyRevalidationErrors(error),
});
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { toCanvasSignedDataApiArgs } from '@hicommonwealth/shared';
import { useQueryClient } from '@tanstack/react-query';
import { trpc } from 'client/scripts/utils/trpcClient';
import { signDeleteCommentReaction } from 'controllers/server/sessions';
import { trpc } from 'utils/trpcClient';
import { useAuthModalStore } from '../../ui/modals';
import { userStore } from '../../ui/user';

Expand Down Expand Up @@ -31,48 +30,17 @@ export const buildDeleteCommentReactionInput = async ({
};
};

interface UseDeleteCommentReactionMutationProps {
communityId: string;
threadId: number;
commentId: number;
}

const useDeleteCommentReactionMutation = ({
threadId,
commentId,
communityId,
}: UseDeleteCommentReactionMutationProps) => {
const queryClient = useQueryClient();
// TODO: fix cache updates
const comments = [];
// const { data: comments } = useFetchCommentsQuery({
// communityId,
// threadId,
// });
const useDeleteCommentReactionMutation = () => {
const utils = trpc.useUtils();

const { checkForSessionKeyRevalidationErrors } = useAuthModalStore();

return trpc.thread.deleteReaction.useMutation({
onSuccess: async (deleted, variables) => {
// // update fetch comments query state
// if (deleted) {
// const key = [ApiEndpoints.FETCH_COMMENTS, communityId, threadId];
// await queryClient.cancelQueries({ queryKey: key });
// queryClient.setQueryData(key, () => {
// const tempComments = [...comments];
// return tempComments.map((comment) => {
// if (comment.id === commentId) {
// return {
// ...comment,
// reactions: comment.reactions.filter(
// (r) => r.id !== variables.reaction_id,
// ),
// };
// }
// return comment;
// });
// });
// }
onSuccess: async () => {
// TODO: #8015 - make a generic util to apply cache
// updates for comments in all possible key combinations
// present in cache.
utils.comment.getComments.invalidate();
},
onError: (error) => checkForSessionKeyRevalidationErrors(error),
});
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { toCanvasSignedDataApiArgs } from '@hicommonwealth/shared';
import { useQueryClient } from '@tanstack/react-query';
import { trpc } from 'client/scripts/utils/trpcClient';
import { signUpdateComment } from 'controllers/server/sessions';
import Comment from 'models/Comment';
import { IUniqueId } from 'models/interfaces';
import { trpc } from 'utils/trpcClient';
import { UserProfile } from '../../../models/MinimumProfile';
import { useAuthModalStore } from '../../ui/modals';
import { userStore } from '../../ui/user';
import { updateThreadInAllCaches } from '../threads/helpers/cache';

interface EditCommentProps {
profile: UserProfile;
Expand Down Expand Up @@ -46,34 +48,27 @@ const useEditCommentMutation = ({
communityId,
threadId,
}: UseEditCommentMutationProps) => {
const queryClient = useQueryClient();
// TODO: fix cache updates
const comments = [];
// const { data: comments } = useFetchCommentsQuery({
// communityId,
// threadId,
// });
const utils = trpc.useUtils();

const { checkForSessionKeyRevalidationErrors } = useAuthModalStore();

return trpc.comment.updateComment.useMutation({
onSuccess: async (updatedComment) => {
// // @ts-expect-error StrictNullChecks
// const comment = new Comment(updatedComment);
// // update fetch comments query state with updated comment
// const key = [ApiEndpoints.FETCH_COMMENTS, communityId, threadId];
// queryClient.cancelQueries({ queryKey: key });
// queryClient.setQueryData([...key], () => {
// // find the existing comment index, and return updated comment in its place
// return comments.map((x) => (x.id === comment.id ? comment : x));
// });
// updateThreadInAllCaches(
// communityId,
// threadId,
// { recentComments: [comment] },
// 'combineAndRemoveDups',
// );
// return comment;
// @ts-expect-error StrictNullChecks
const comment = new Comment(updatedComment);

// TODO: #8015 - make a generic util to apply cache
// updates for comments in all possible key combinations
// present in cache.
utils.comment.getComments.invalidate();

updateThreadInAllCaches(
communityId,
threadId,
{ recentComments: [comment as Comment<IUniqueId>] },
'combineAndRemoveDups',
);
return comment;
},
onError: (error) => checkForSessionKeyRevalidationErrors(error),
});
Expand Down
Loading

0 comments on commit 308f1db

Please sign in to comment.