Skip to content

Commit 04fb5d3

Browse files
committed
Move delete to react-query
1 parent 1a6fcfb commit 04fb5d3

File tree

5 files changed

+48
-100
lines changed

5 files changed

+48
-100
lines changed

site/src/api/queries/users.ts

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,12 @@ export const updatePassword = () => {
1919
};
2020
};
2121

22-
export const createUser = () => {
22+
export const createUser = (queryClient: QueryClient) => {
2323
return {
2424
mutationFn: API.createUser,
25+
onSuccess: async () => {
26+
await queryClient.invalidateQueries(["users"]);
27+
},
2528
};
2629
};
2730

@@ -48,3 +51,12 @@ export const activateUser = (queryClient: QueryClient) => {
4851
},
4952
};
5053
};
54+
55+
export const deleteUser = (queryClient: QueryClient) => {
56+
return {
57+
mutationFn: API.deleteUser,
58+
onSuccess: async () => {
59+
await queryClient.invalidateQueries(["users"]);
60+
},
61+
};
62+
};

site/src/pages/CreateUserPage/CreateUserPage.tsx

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import { CreateUserForm } from "./CreateUserForm";
66
import { Margins } from "components/Margins/Margins";
77
import { pageTitle } from "utils/page";
88
import { getAuthMethods } from "api/api";
9-
import { useMutation, useQuery } from "@tanstack/react-query";
9+
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
1010
import { createUser } from "api/queries/users";
1111
import { displaySuccess } from "components/GlobalSnackbar/utils";
1212

@@ -17,7 +17,8 @@ export const Language = {
1717
export const CreateUserPage: FC = () => {
1818
const myOrgId = useOrganizationId();
1919
const navigate = useNavigate();
20-
const createUserMutation = useMutation(createUser());
20+
const queryClient = useQueryClient();
21+
const createUserMutation = useMutation(createUser(queryClient));
2122
// TODO: We should probably place this somewhere else to reduce the number of calls.
2223
// This would be called each time this page is loaded.
2324
const { data: authMethods } = useQuery({

site/src/pages/UsersPage/UsersPage.test.tsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -252,7 +252,7 @@ describe("UsersPage", () => {
252252
});
253253

254254
// Check if the success message is displayed
255-
await screen.findByText(usersXServiceLanguage.deleteUserSuccess);
255+
await screen.findByText("User deleted");
256256

257257
// Check if the API was called correctly
258258
expect(API.deleteUser).toBeCalledTimes(1);
@@ -274,7 +274,7 @@ describe("UsersPage", () => {
274274
});
275275

276276
// Check if the error message is displayed
277-
await screen.findByText(usersXServiceLanguage.deleteUserError);
277+
await screen.findByText("Error deleting user");
278278

279279
// Check if the API was called correctly
280280
expect(API.deleteUser).toBeCalledTimes(1);

site/src/pages/UsersPage/UsersPage.tsx

Lines changed: 26 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,12 @@ import { roles } from "api/queries/roles";
2121
import { deploymentConfig } from "api/queries/deployment";
2222
import { prepareQuery } from "utils/filters";
2323
import { usePagination } from "hooks";
24-
import { users, suspendUser, activateUser } from "api/queries/users";
24+
import {
25+
users,
26+
suspendUser,
27+
activateUser,
28+
deleteUser,
29+
} from "api/queries/users";
2530
import { displayError, displaySuccess } from "components/GlobalSnackbar/utils";
2631
import { getErrorMessage } from "api/errors";
2732

@@ -55,8 +60,7 @@ export const UsersPage: FC<{ children?: ReactNode }> = () => {
5560
offset: pagination.offset,
5661
}),
5762
);
58-
const { usernameToDelete, userIdToResetPassword, newUserPassword } =
59-
usersState.context;
63+
const { userIdToResetPassword, newUserPassword } = usersState.context;
6064
const { updateUsers: canEditUsers, viewDeploymentValues } = usePermissions();
6165
const rolesQuery = useQuery({ ...roles(), enabled: canEditUsers });
6266
const { data: deploymentValues } = useQuery({
@@ -91,10 +95,15 @@ export const UsersPage: FC<{ children?: ReactNode }> = () => {
9195
});
9296
const isLoading =
9397
usersQuery.isLoading || rolesQuery.isLoading || authMethods.isLoading;
98+
// Suspend
9499
const [confirmSuspendUser, setConfirmSuspendUser] = useState<User>();
95100
const suspendUserMutation = useMutation(suspendUser(queryClient));
101+
// Activate
96102
const [confirmActivateUser, setConfirmActivateUser] = useState<User>();
97103
const activateUserMutation = useMutation(activateUser(queryClient));
104+
// Delete
105+
const [confirmDeleteUser, setConfirmDeleteUser] = useState<User>();
106+
const deleteUserMutation = useMutation(deleteUser(queryClient));
98107

99108
return (
100109
<>
@@ -117,13 +126,7 @@ export const UsersPage: FC<{ children?: ReactNode }> = () => {
117126
"/audit?filter=" + encodeURIComponent(`username:${user.username}`),
118127
);
119128
}}
120-
onDeleteUser={(user) => {
121-
usersSend({
122-
type: "DELETE_USER",
123-
userId: user.id,
124-
username: user.username,
125-
});
126-
}}
129+
onDeleteUser={setConfirmDeleteUser}
127130
onSuspendUser={setConfirmSuspendUser}
128131
onActivateUser={setConfirmActivateUser}
129132
onResetUserPassword={(user) => {
@@ -156,19 +159,22 @@ export const UsersPage: FC<{ children?: ReactNode }> = () => {
156159
/>
157160

158161
<DeleteDialog
159-
key={usernameToDelete}
160-
isOpen={
161-
usersState.matches("confirmUserDeletion") ||
162-
usersState.matches("deletingUser")
163-
}
164-
confirmLoading={usersState.matches("deletingUser")}
165-
name={usernameToDelete ?? ""}
162+
key={confirmDeleteUser?.username}
163+
isOpen={confirmDeleteUser !== undefined}
164+
confirmLoading={deleteUserMutation.isLoading}
165+
name={confirmDeleteUser?.username ?? ""}
166166
entity="user"
167-
onConfirm={() => {
168-
usersSend("CONFIRM_USER_DELETE");
167+
onConfirm={async () => {
168+
try {
169+
await deleteUserMutation.mutateAsync(confirmDeleteUser!.id);
170+
setConfirmDeleteUser(undefined);
171+
displaySuccess("User deleted");
172+
} catch (e) {
173+
displayError(getErrorMessage(e, "Error deleting user"));
174+
}
169175
}}
170176
onCancel={() => {
171-
usersSend("CANCEL_USER_DELETE");
177+
setConfirmDeleteUser(undefined);
172178
}}
173179
/>
174180

site/src/xServices/users/usersXService.ts

Lines changed: 4 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -6,19 +6,13 @@ import { displayError, displaySuccess } from "components/GlobalSnackbar/utils";
66
import { generateRandomString } from "utils/random";
77

88
export const Language = {
9-
deleteUserSuccess: "Successfully deleted the user.",
10-
deleteUserError: "Error deleting user.",
119
resetUserPasswordSuccess: "Successfully updated the user password.",
1210
resetUserPasswordError: "Error on resetting the user password.",
1311
updateUserRolesSuccess: "Successfully updated the user roles.",
1412
updateUserRolesError: "Error on updating the user roles.",
1513
};
1614

1715
export interface UsersContext {
18-
// Delete user
19-
userIdToDelete?: TypesGen.User["id"];
20-
usernameToDelete?: TypesGen.User["username"];
21-
deleteUserError?: unknown;
2216
// Reset user password
2317
userIdToResetPassword?: TypesGen.User["id"];
2418
resetUserPasswordError?: unknown;
@@ -29,14 +23,6 @@ export interface UsersContext {
2923
}
3024

3125
export type UsersEvent =
32-
// Delete events
33-
| {
34-
type: "DELETE_USER";
35-
userId: TypesGen.User["id"];
36-
username: TypesGen.User["username"];
37-
}
38-
| { type: "CONFIRM_USER_DELETE" }
39-
| { type: "CANCEL_USER_DELETE" }
4026
// Reset password events
4127
| { type: "RESET_USER_PASSWORD"; userId: TypesGen.User["id"] }
4228
| { type: "CONFIRM_USER_PASSWORD_RESET" }
@@ -84,10 +70,6 @@ export const usersMachine =
8470
idle: {
8571
entry: "clearSelectedUser",
8672
on: {
87-
DELETE_USER: {
88-
target: "confirmUserDeletion",
89-
actions: "assignUserToDelete",
90-
},
9173
RESET_USER_PASSWORD: {
9274
target: "confirmUserPasswordReset",
9375
actions: [
@@ -101,35 +83,6 @@ export const usersMachine =
10183
},
10284
},
10385
},
104-
confirmUserDeletion: {
105-
on: {
106-
CONFIRM_USER_DELETE: {
107-
target: "deletingUser",
108-
},
109-
CANCEL_USER_DELETE: {
110-
target: "idle",
111-
},
112-
},
113-
},
114-
deletingUser: {
115-
entry: "clearDeleteUserError",
116-
invoke: {
117-
src: "deleteUser",
118-
id: "deleteUser",
119-
onDone: [
120-
{
121-
target: "idle",
122-
actions: "displayDeleteSuccess",
123-
},
124-
],
125-
onError: [
126-
{
127-
target: "idle",
128-
actions: ["assignDeleteUserError", "displayDeleteErrorMessage"],
129-
},
130-
],
131-
},
132-
},
13386
confirmUserPasswordReset: {
13487
on: {
13588
CONFIRM_USER_PASSWORD_RESET: {
@@ -188,12 +141,6 @@ export const usersMachine =
188141
},
189142
{
190143
services: {
191-
deleteUser: (context) => {
192-
if (!context.userIdToDelete) {
193-
throw new Error("userIdToDelete is undefined");
194-
}
195-
return API.deleteUser(context.userIdToDelete);
196-
},
197144
resetUserPassword: (context) => {
198145
if (!context.userIdToResetPassword) {
199146
throw new Error("userIdToResetPassword is undefined");
@@ -219,49 +166,31 @@ export const usersMachine =
219166

220167
actions: {
221168
clearSelectedUser: assign({
222-
userIdToDelete: (_) => undefined,
223-
usernameToDelete: (_) => undefined,
224169
userIdToResetPassword: (_) => undefined,
225170
userIdToUpdateRoles: (_) => undefined,
226171
}),
227-
assignUserToDelete: assign({
228-
userIdToDelete: (_, event) => event.userId,
229-
usernameToDelete: (_, event) => event.username,
230-
}),
172+
231173
assignUserIdToResetPassword: assign({
232174
userIdToResetPassword: (_, event) => event.userId,
233175
}),
234176
assignUserIdToUpdateRoles: assign({
235177
userIdToUpdateRoles: (_, event) => event.userId,
236178
}),
237-
assignDeleteUserError: assign({
238-
deleteUserError: (_, event) => event.data,
239-
}),
179+
240180
assignResetUserPasswordError: assign({
241181
resetUserPasswordError: (_, event) => event.data,
242182
}),
243183
assignUpdateRolesError: assign({
244184
updateUserRolesError: (_, event) => event.data,
245185
}),
246-
clearDeleteUserError: assign({
247-
deleteUserError: (_) => undefined,
248-
}),
186+
249187
clearResetUserPasswordError: assign({
250188
resetUserPasswordError: (_) => undefined,
251189
}),
252190
clearUpdateUserRolesError: assign({
253191
updateUserRolesError: (_) => undefined,
254192
}),
255-
displayDeleteSuccess: () => {
256-
displaySuccess(Language.deleteUserSuccess);
257-
},
258-
displayDeleteErrorMessage: (context) => {
259-
const message = getErrorMessage(
260-
context.deleteUserError,
261-
Language.deleteUserError,
262-
);
263-
displayError(message);
264-
},
193+
265194
displayResetPasswordSuccess: () => {
266195
displaySuccess(Language.resetUserPasswordSuccess);
267196
},

0 commit comments

Comments
 (0)