Skip to content

Commit

Permalink
fix(profile): prevent state reset on app refresh
Browse files Browse the repository at this point in the history
  • Loading branch information
rhahao authored Nov 26, 2024
1 parent 276fb4e commit 5102518
Showing 1 changed file with 26 additions and 12 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useEffect, useState } from 'react';
import { useEffect, useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { apiUserDelete } from '@services/api/user';
import { displaySnackNotification } from '@services/recoil/app';
import { useAppTranslation, useCurrentUser } from '@hooks/index';
Expand All @@ -26,6 +27,28 @@ const useDeleteAccount = (closeDialog: VoidFunction) => {
const [isDeleteCong, setIsDeleteCong] = useState(false);
const [isManageAccess, setIsManageAccess] = useState(false);

const { data } = useQuery({
queryKey: ['admin-users'],
queryFn: apiCongregationUsersGet,
enabled: isAdmin,
});

const users = useMemo(() => {
if (!data) return [];
if (!Array.isArray(data.users)) return [];

return data.users;
}, [data]);

const adminCount = useMemo(() => {
return users.filter((user) =>
user.profile.cong_role.some(
(role) =>
role === 'admin' || role === 'coordinator' || role === 'secretary'
)
).length;
}, [users]);

const handleDelete = async () => {
if (isProcessing) return;

Expand Down Expand Up @@ -63,30 +86,21 @@ const useDeleteAccount = (closeDialog: VoidFunction) => {

useEffect(() => {
const loadDetails = async () => {
setIsDeleteCong(false);
setIsManageAccess(false);

try {
if (!isAdmin) {
setDesc(t('tr_deleteAccountDesc'));
setIsLoading(false);
return;
}

const { users } = await apiCongregationUsersGet();

if (users.length === 1) {
setDesc(t('tr_deleteAccountWithCongregationDesc'));
setIsDeleteCong(true);
setIsLoading(false);
return;
}

const admins = users.filter((user) =>
user.profile.cong_role.includes('admin')
).length;

if (admins > 1) {
if (adminCount > 1) {
setDesc(t('tr_deleteAccountDesc'));
setIsLoading(false);
return;
Expand All @@ -107,7 +121,7 @@ const useDeleteAccount = (closeDialog: VoidFunction) => {
};

loadDetails();
}, [isAdmin, t, closeDialog]);
}, [isAdmin, t, closeDialog, users, adminCount]);

return {
isProcessing,
Expand Down

0 comments on commit 5102518

Please sign in to comment.