Skip to content

Commit

Permalink
improve query keys
Browse files Browse the repository at this point in the history
  • Loading branch information
alan2207 committed May 14, 2024
1 parent 60d95a3 commit 7ddd5c4
Show file tree
Hide file tree
Showing 11 changed files with 75 additions and 43 deletions.
16 changes: 9 additions & 7 deletions src/features/comments/api/create-comment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import { useNotificationStore } from '@/stores/notifications';

import { Comment } from '../types';

import { getCommentsKey } from './get-comments';

export const createCommentInputSchema = z.object({
discussionId: z.string().min(1, 'Required'),
body: z.string().min(1, 'Required'),
Expand Down Expand Up @@ -37,32 +39,32 @@ export const useCreateComment = ({
return useMutation({
onMutate: async (newComment) => {
await queryClient.cancelQueries({
queryKey: ['comments', discussionId],
queryKey: getCommentsKey(discussionId),
});

const previousComments = queryClient.getQueryData<Comment[]>([
'comments',
discussionId,
]);

queryClient.setQueryData(
['comments', discussionId],
[...(previousComments || []), newComment.data],
);
queryClient.setQueryData(getCommentsKey(discussionId), [
...(previousComments || []),
newComment.data,
]);

return { previousComments };
},
onError: (_, __, context: any) => {
if (context?.previousComments) {
queryClient.setQueryData(
['comments', discussionId],
getCommentsKey(discussionId),
context.previousComments,
);
}
},
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ['comments', discussionId],
queryKey: getCommentsKey(discussionId),
});
addNotification({
type: 'success',
Expand Down
10 changes: 6 additions & 4 deletions src/features/comments/api/delete-comment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import { useNotificationStore } from '@/stores/notifications';

import { Comment } from '../types';

import { getCommentsKey } from './get-comments';

export const deleteComment = ({ commentId }: { commentId: string }) => {
return api.delete(`/comments/${commentId}`);
};
Expand All @@ -25,7 +27,7 @@ export const useDeleteComment = ({
return useMutation({
onMutate: async (deletedComment) => {
await queryClient.cancelQueries({
queryKey: ['comments', discussionId],
queryKey: getCommentsKey(discussionId),
});

const previousComments = queryClient.getQueryData<Comment[]>([
Expand All @@ -34,7 +36,7 @@ export const useDeleteComment = ({
]);

queryClient.setQueryData(
['comments', discussionId],
getCommentsKey(discussionId),
previousComments?.filter(
(comment) => comment.id !== deletedComment.commentId,
),
Expand All @@ -45,14 +47,14 @@ export const useDeleteComment = ({
onError: (_, __, context: any) => {
if (context?.previousComments) {
queryClient.setQueryData(
['comments', discussionId],
getCommentsKey(discussionId),
context.previousComments,
);
}
},
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ['comments', discussionId],
queryKey: getCommentsKey(discussionId),
});
addNotification({
type: 'success',
Expand Down
7 changes: 6 additions & 1 deletion src/features/comments/api/get-comments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,19 @@ export const getComments = ({

type QueryFnType = typeof getComments;

export const getCommentsKey = (discussionId: string) => [
'comments',
discussionId,
];

type UseCommentsOptions = {
discussionId: string;
config?: QueryConfig<QueryFnType>;
};

export const useComments = ({ discussionId, config }: UseCommentsOptions) => {
return useQuery<ApiFnReturnType<QueryFnType>>({
queryKey: ['comments', discussionId],
queryKey: getCommentsKey(discussionId),
queryFn: () => getComments({ discussionId }),
...config,
});
Expand Down
24 changes: 14 additions & 10 deletions src/features/discussions/api/create-discussion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import { useNotificationStore } from '@/stores/notifications';

import { Discussion } from '../types';

import { getDiscussionsKey } from './get-discussions';

export const createDiscussionInputSchema = z.object({
title: z.string().min(1, 'Required'),
body: z.string().min(1, 'Required'),
Expand Down Expand Up @@ -35,28 +37,30 @@ export const useCreateDiscussion = ({
return useMutation({
onMutate: async (newDiscussion) => {
await queryClient.cancelQueries({
queryKey: ['discussions'],
queryKey: getDiscussionsKey(),
});

const previousDiscussions = queryClient.getQueryData<Discussion[]>([
'discussions',
]);
const previousDiscussions =
queryClient.getQueryData<Discussion[]>(getDiscussionsKey());

queryClient.setQueryData(
['discussions'],
[...(previousDiscussions || []), newDiscussion.data],
);
queryClient.setQueryData(getDiscussionsKey(), [
...(previousDiscussions || []),
newDiscussion.data,
]);

return { previousDiscussions };
},
onError: (_, __, context: any) => {
if (context?.previousDiscussions) {
queryClient.setQueryData(['discussions'], context.previousDiscussions);
queryClient.setQueryData(
getDiscussionsKey(),
context.previousDiscussions,
);
}
},
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ['discussions'],
queryKey: getDiscussionsKey(),
});
addNotification({
type: 'success',
Expand Down
18 changes: 11 additions & 7 deletions src/features/discussions/api/delete-discussion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import { useNotificationStore } from '@/stores/notifications';

import { Discussion } from '../types';

import { getDiscussionsKey } from './get-discussions';

export const deleteDiscussion = ({
discussionId,
}: {
Expand All @@ -27,15 +29,14 @@ export const useDeleteDiscussion = ({
return useMutation({
onMutate: async (deletedDiscussion) => {
await queryClient.cancelQueries({
queryKey: ['discussions'],
queryKey: getDiscussionsKey(),
});

const previousDiscussions = queryClient.getQueryData<Discussion[]>([
'discussions',
]);
const previousDiscussions =
queryClient.getQueryData<Discussion[]>(getDiscussionsKey());

queryClient.setQueryData(
['discussions'],
getDiscussionsKey(),
previousDiscussions?.filter(
(discussion) => discussion.id !== deletedDiscussion.discussionId,
),
Expand All @@ -45,12 +46,15 @@ export const useDeleteDiscussion = ({
},
onError: (_, __, context: any) => {
if (context?.previousDiscussions) {
queryClient.setQueryData(['discussions'], context.previousDiscussions);
queryClient.setQueryData(
getDiscussionsKey(),
context.previousDiscussions,
);
}
},
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ['discussions'],
queryKey: getDiscussionsKey(),
});
addNotification({
type: 'success',
Expand Down
7 changes: 6 additions & 1 deletion src/features/discussions/api/get-discussion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ export const getDiscussion = ({

type QueryFnType = typeof getDiscussion;

export const getDiscussionKey = (discussionId: string) => [
'discussions',
discussionId,
];

type UseDiscussionOptions = {
discussionId: string;
config?: QueryConfig<QueryFnType>;
Expand All @@ -26,7 +31,7 @@ export const useDiscussion = ({
}: UseDiscussionOptions) => {
return useQuery<ApiFnReturnType<QueryFnType>>({
...config,
queryKey: ['discussion', discussionId],
queryKey: getDiscussionKey(discussionId),
queryFn: () => getDiscussion({ discussionId }),
});
};
4 changes: 3 additions & 1 deletion src/features/discussions/api/get-discussions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,16 @@ export const getDiscussions = (): Promise<Discussion[]> => {

type QueryFnType = typeof getDiscussions;

export const getDiscussionsKey = () => ['discussions'];

type UseDiscussionsOptions = {
config?: QueryConfig<QueryFnType>;
};

export const useDiscussions = ({ config }: UseDiscussionsOptions = {}) => {
return useQuery<ApiFnReturnType<QueryFnType>>({
...config,
queryKey: ['discussions'],
queryKey: getDiscussionsKey(),
queryFn: () => getDiscussions(),
});
};
12 changes: 7 additions & 5 deletions src/features/discussions/api/update-discussion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import { useNotificationStore } from '@/stores/notifications';

import { Discussion } from '../types';

import { getDiscussionKey } from './get-discussion';

export const updateDiscussionInputSchema = z.object({
title: z.string().min(1, 'Required'),
body: z.string().min(1, 'Required'),
Expand Down Expand Up @@ -35,9 +37,9 @@ export const useUpdateDiscussion = ({
const queryClient = useQueryClient();

return useMutation({
onMutate: async (updatingDiscussion: any) => {
onMutate: async (updatingDiscussion) => {
await queryClient.cancelQueries({
queryKey: ['discussion', updatingDiscussion?.discussionId],
queryKey: getDiscussionKey(updatingDiscussion.discussionId),
});

const previousDiscussion = queryClient.getQueryData<Discussion>([
Expand All @@ -46,7 +48,7 @@ export const useUpdateDiscussion = ({
]);

queryClient.setQueryData(
['discussion', updatingDiscussion?.discussionId],
getDiscussionKey(updatingDiscussion.discussionId),
{
...previousDiscussion,
...updatingDiscussion.data,
Expand All @@ -59,14 +61,14 @@ export const useUpdateDiscussion = ({
onError: (_, __, context: any) => {
if (context?.previousDiscussion) {
queryClient.setQueryData(
['discussion', context.previousDiscussion.id],
getDiscussionKey(context.previousDiscussion.id),
context.previousDiscussion,
);
}
},
onSuccess: (data) => {
queryClient.refetchQueries({
queryKey: ['discussion', data.id],
queryKey: getDiscussionKey(data.id),
});
addNotification({
type: 'success',
Expand Down
4 changes: 3 additions & 1 deletion src/features/teams/api/get-teams.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,16 @@ export const getTeams = (): Promise<Team[]> => {

type QueryFnType = typeof getTeams;

export const getTeamsKey = () => ['teams'];

type UseTeamsOptions = {
config?: QueryConfig<QueryFnType>;
};

export const useTeams = ({ config = {} }: UseTeamsOptions = {}) => {
return useQuery<ApiFnReturnType<QueryFnType>>({
...config,
queryKey: ['teams'],
queryKey: getTeamsKey(),
queryFn: () => getTeams(),
});
};
12 changes: 7 additions & 5 deletions src/features/users/api/delete-user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import { useNotificationStore } from '@/stores/notifications';

import { User } from '../types';

import { getUsersKey } from './get-users';

export type DeleteUserDTO = {
userId: string;
};
Expand All @@ -25,26 +27,26 @@ export const useDeleteUser = ({ config }: UseDeleteUserOptions = {}) => {
return useMutation({
onMutate: async (deletedUser) => {
await queryClient.cancelQueries({
queryKey: ['users'],
queryKey: getUsersKey(),
});

const previousUsers = queryClient.getQueryData<User[]>(['users']);
const previousUsers = queryClient.getQueryData<User[]>(getUsersKey());

queryClient.setQueryData(
['users'],
getUsersKey(),
previousUsers?.filter((user) => user.id !== deletedUser.userId),
);

return { previousUsers };
},
onError: (_, __, context: any) => {
if (context?.previousUsers) {
queryClient.setQueryData(['users'], context.previousUsers);
queryClient.setQueryData(getUsersKey(), context.previousUsers);
}
},
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ['users'],
queryKey: getUsersKey(),
});
addNotification({
type: 'success',
Expand Down
4 changes: 3 additions & 1 deletion src/features/users/api/get-users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,16 @@ export const getUsers = (): Promise<User[]> => {

type QueryFnType = typeof getUsers;

export const getUsersKey = () => ['users'];

type UseUsersOptions = {
config?: QueryConfig<QueryFnType>;
};

export const useUsers = ({ config }: UseUsersOptions = {}) => {
return useQuery<ApiFnReturnType<QueryFnType>>({
...config,
queryKey: ['users'],
queryKey: getUsersKey(),
queryFn: () => getUsers(),
});
};

0 comments on commit 7ddd5c4

Please sign in to comment.