Skip to content

Commit

Permalink
refactor: react query status on useeffect & toast messages (#1423)
Browse files Browse the repository at this point in the history
Co-authored-by: JoaoSaIvador <j.salvador@kigroup.de>
  • Loading branch information
StereoPT and jpvsalvador authored Apr 21, 2023
1 parent 1d952cf commit 4a7ac92
Show file tree
Hide file tree
Showing 18 changed files with 190 additions and 229 deletions.
8 changes: 2 additions & 6 deletions frontend/src/components/Board/DragDropArea/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import { useRecoilState, useRecoilValue, useSetRecoilState } from 'recoil';

import Column from '@/components/Board/Column/Column';
import Flex from '@/components/Primitives/Layout/Flex/Flex';
import { createInfoMessage } from '@/constants/toasts';
import { BoardUserRoles } from '@/enums/boards/userRoles';
import { ToastStateEnum } from '@/enums/toasts/toast-types';
import { countBoardCards } from '@/helper/board/countCards';
import useBoard from '@/hooks/useBoard';
import useCards from '@/hooks/useCards';
Expand Down Expand Up @@ -94,11 +94,7 @@ const DragDropArea: React.FC<Props> = ({

mergeCards.mutate(changes);
} else if (board.hideCards) {
setToastState({
open: true,
type: ToastStateEnum.INFO,
content: 'The merge is not possible. The cards are hidden',
});
setToastState(createInfoMessage('The merge is not possible. The cards are hidden.'));
}
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import EmptyTeamBoards from '@/components/Boards/MyBoards/ListBoardsByTeam/Empty
import { ScrollableContent } from '@/components/Boards/MyBoards/styles';
import TeamHeader from '@/components/Boards/TeamHeader';
import Flex from '@/components/Primitives/Layout/Flex/Flex';
import { ToastStateEnum } from '@/enums/toasts/toast-types';
import { createErrorMessage } from '@/constants/toasts';
import { toastState } from '@/store/toast/atom/toast.atom';
import BoardType from '@/types/board/board';
import { Team } from '@/types/team/team';
Expand All @@ -35,11 +35,7 @@ const ListBoardsByTeam = ({ filteredTeam, userId, isSuperAdmin }: ListBoardsByTe
return undefined;
},
onError: () => {
setToastState({
open: true,
content: 'Error getting the boards',
type: ToastStateEnum.ERROR,
});
setToastState(createErrorMessage('Error getting the boards'));
},
},
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { getPersonalBoardsRequest } from '@/api/boardService';
import ListBoards from '@/components/Boards/MyBoards/ListBoards';
import EmptyPersonalBoards from '@/components/Boards/MyBoards/ListPersonalBoards/EmptyPersonalBoards';
import Flex from '@/components/Primitives/Layout/Flex/Flex';
import { ToastStateEnum } from '@/enums/toasts/toast-types';
import { createErrorMessage } from '@/constants/toasts';
import { toastState } from '@/store/toast/atom/toast.atom';
import BoardType from '@/types/board/board';
import { Team } from '@/types/team/team';
Expand All @@ -32,11 +32,7 @@ const ListPersonalBoards = ({ userId, isSuperAdmin }: ListBoardsByTeamProps) =>
return undefined;
},
onError: () => {
setToastState({
open: true,
content: 'Error getting the boards',
type: ToastStateEnum.ERROR,
});
setToastState(createErrorMessage('Error getting the boards'));
},
},
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import React, { Dispatch, SetStateAction } from 'react';
import { useRecoilState, useSetRecoilState } from 'recoil';

import UserListDialog from '@/components/Primitives/Dialogs/UserListDialog/UserListDialog';
import { createSuccessMessage } from '@/constants/toasts';
import { BoardUserRoles } from '@/enums/boards/userRoles';
import { ToastStateEnum } from '@/enums/toasts/toast-types';
import useCurrentSession from '@/hooks/useCurrentSession';
import { createBoardDataState } from '@/store/createBoard/atoms/create-board.atom';
import { toastState } from '@/store/toast/atom/toast.atom';
Expand Down Expand Up @@ -65,11 +65,7 @@ const ListParticipants = ({ isOpen, setIsOpen }: ListParticipantsProps) => {
board: { ...prev.board, team: null },
}));

setToastState({
open: true,
content: 'Board participant/s successfully updated',
type: ToastStateEnum.SUCCESS,
});
setToastState(createSuccessMessage('Board participant/s successfully updated'));

setIsOpen(false);
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ import ParticipantsTab from '@/components/CreateBoard/RegularBoard/ParticipantsT
import Flex from '@/components/Primitives/Layout/Flex/Flex';
import Tab, { TabList } from '@/components/Primitives/Tab/Tab';
import Text from '@/components/Primitives/Text/Text';
import { createErrorMessage } from '@/constants/toasts';
import { BoardUserRoles } from '@/enums/boards/userRoles';
import { ToastStateEnum } from '@/enums/toasts/toast-types';
import useCurrentSession from '@/hooks/useCurrentSession';
import {
createBoardDataState,
Expand Down Expand Up @@ -69,11 +69,9 @@ const SettingsTabs = ({ isPageLoading }: SettingsTabsProps) => {

if (errors.team && activeTab === 'config') {
handleTabChange('participants');
setToastState({
open: true,
content: 'Please choose a team in the "Team/-Sub-teams configuration" tab',
type: ToastStateEnum.ERROR,
});
setToastState(
createErrorMessage('Please choose a team in the "Team/-Sub-teams configuration" tab'),
);
}
}, [activeTab, errors.maxVotes, errors.team, setToastState]);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import SubTeamsConfigurations from '@/components/CreateBoard/SplitBoard/SubTeams
import Flex from '@/components/Primitives/Layout/Flex/Flex';
import Tab, { TabList } from '@/components/Primitives/Tab/Tab';
import Text from '@/components/Primitives/Text/Text';
import { ToastStateEnum } from '@/enums/toasts/toast-types';
import { createErrorMessage } from '@/constants/toasts';
import { createBoardError, createBoardTeam } from '@/store/createBoard/atoms/create-board.atom';
import { toastState } from '@/store/toast/atom/toast.atom';
import { usePrevious } from '@/utils/previousState';
Expand Down Expand Up @@ -50,11 +50,9 @@ const SettingsTabs = () => {

if (errors.team && activeTab === 'config') {
handleTabChange('teams');
setToastState({
open: true,
content: 'Please choose a team in the "Team/-Sub-teams configuration" tab',
type: ToastStateEnum.ERROR,
});
setToastState(
createErrorMessage('Please choose a team in the "Team/-Sub-teams configuration" tab'),
);
}
}, [activeTab, errors.maxVotes, errors.team, setToastState]);

Expand Down
8 changes: 2 additions & 6 deletions frontend/src/components/Dashboard/RecentRetros/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { useSetRecoilState } from 'recoil';
import { getDashboardBoardsRequest } from '@/api/boardService';
import EmptyBoards from '@/components/Dashboard/RecentRetros/partials/EmptyBoards';
import ListOfCards from '@/components/Dashboard/RecentRetros/partials/ListOfCards';
import { ToastStateEnum } from '@/enums/toasts/toast-types';
import { createErrorMessage } from '@/constants/toasts';
import { toastState } from '@/store/toast/atom/toast.atom';
import isEmpty from '@/utils/isEmpty';

Expand All @@ -28,11 +28,7 @@ const RecentRetros = React.memo<RecentRetrosProp>(({ userId }) => {
return undefined;
},
onError: () => {
setToastState({
open: true,
content: 'Error getting the boards',
type: ToastStateEnum.ERROR,
});
setToastState(createErrorMessage('Error getting the boards'));
},
},
);
Expand Down
3 changes: 1 addition & 2 deletions frontend/src/components/Teams/CreateTeam/CreateTeam.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,7 @@ describe('Teams/CreateTeam', () => {
// Assert

await waitFor(() => {
expect(createTeamMutation).toBeCalledWith({ name: 'MyTeam', users: [] });
expect(mockRouter.push).toHaveBeenCalledWith(ROUTES.Teams);
expect(createTeamMutation).toBeCalledWith({ name: 'MyTeam', users: [] }, expect.anything());
});
});

Expand Down
26 changes: 13 additions & 13 deletions frontend/src/components/Teams/CreateTeam/CreateTeam.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useState } from 'react';
import { useCallback, useState } from 'react';
import { FormProvider, useForm } from 'react-hook-form';
import { useRouter } from 'next/router';
import { joiResolver } from '@hookform/resolvers/joi';
Expand Down Expand Up @@ -28,7 +28,7 @@ const CreateTeam = () => {
const { userId } = useCurrentSession();
const { back, push } = useRouter();

const { mutate: createTeam, status } = useCreateTeam();
const { mutate: createTeam } = useCreateTeam();

const [disableButtons, setDisableButtons] = useState(false);
const [isOpen, setIsOpen] = useState(false);
Expand Down Expand Up @@ -59,7 +59,17 @@ const CreateTeam = () => {
user: member.user._id,
}));

createTeam({ name: title, users: membersListToSubmit });
createTeam(
{ name: title, users: membersListToSubmit },
{
onSuccess: () => {
push(ROUTES.Teams);
},
onError: () => {
setDisableButtons(false);
},
},
);
resetListUsersState();
};

Expand All @@ -74,16 +84,6 @@ const CreateTeam = () => {
setIsOpen(true);
};

useEffect(() => {
if (status === 'error') {
setDisableButtons(false);
}

if (status === 'success') {
push(ROUTES.Teams);
}
}, [status]);

return (
<Flex
css={{ height: '100vh', backgroundColor: '$primary50' }}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import { useRouter } from 'next/router';
import { useRecoilState, useSetRecoilState } from 'recoil';

import UserListDialog from '@/components/Primitives/Dialogs/UserListDialog/UserListDialog';
import { createSuccessMessage } from '@/constants/toasts';
import { TeamUserRoles } from '@/enums/teams/userRoles';
import { ToastStateEnum } from '@/enums/toasts/toast-types';
import useTeam from '@/hooks/teams/useTeam';
import useUpdateTeamUsers from '@/hooks/teams/useUpdateTeamUsers';
import useCurrentSession from '@/hooks/useCurrentSession';
Expand Down Expand Up @@ -107,11 +107,7 @@ const ListMembers = ({ isOpen, setIsOpen, isTeamPage }: ListMembersProps) => {

updatedListWithAdded.unshift(updatedListWithAdded.splice(userAdminIndex, 1)[0]);

setToastState({
open: true,
content: 'Team member/s successfully updated',
type: ToastStateEnum.SUCCESS,
});
setToastState(createSuccessMessage('Team member/s successfully updated'));

setCreateTeamMembers(updatedListWithAdded);
setUsersList(checkedUserList);
Expand Down
8 changes: 2 additions & 6 deletions frontend/src/components/auth/LoginForm/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import {
NEXT_PUBLIC_LOGIN_SSO_ONLY,
} from '@/constants';
import { DASHBOARD_ROUTE } from '@/constants/routes';
import { ToastStateEnum } from '@/enums/toasts/toast-types';
import { createErrorMessage } from '@/constants/toasts';
import loginWithAzure from '@/hooks/auth/loginWithAzure';
import SchemaLoginForm from '@/schema/schemaLoginForm';
import { toastState } from '@/store/toast/atom/toast.atom';
Expand Down Expand Up @@ -74,11 +74,7 @@ const LoginForm = ({ setShowTroubleLogin }: LoginFormProps) => {

if (result.error) {
methods.reset();
setToastState({
open: true,
type: ToastStateEnum.ERROR,
content: result.error,
});
setToastState(createErrorMessage(result.error));
}

setLoading((prevState) => ({ ...prevState, credentials: false }));
Expand Down
8 changes: 2 additions & 6 deletions frontend/src/components/auth/SignUp/RegisterForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ import Input from '@/components/Primitives/Inputs/Input/Input';
import Flex from '@/components/Primitives/Layout/Flex/Flex';
import Text from '@/components/Primitives/Text/Text';
import { DASHBOARD_ROUTE } from '@/constants/routes';
import { createErrorMessage } from '@/constants/toasts';
import { SignUpEnum } from '@/enums/auth/signUp';
import { ToastStateEnum } from '@/enums/toasts/toast-types';
import SchemaRegisterForm from '@/schema/schemaRegisterForm';
import { toastState } from '@/store/toast/atom/toast.atom';
import { FlexForm } from '@/styles/pages/pages.styles';
Expand Down Expand Up @@ -71,11 +71,7 @@ const RegisterForm = ({
const createUser = useMutation((user: RegisterUser) => registerNewUser(user), {
mutationKey: ['register'],
onError: () => {
setToastState({
open: true,
type: ToastStateEnum.ERROR,
content: 'Something went wrong, please try again',
});
setToastState(createErrorMessage('Something went wrong, please try again'));
},
onSuccess: () => {
setShowSignUp(SignUpEnum.SIGN_UP);
Expand Down
69 changes: 24 additions & 45 deletions frontend/src/components/auth/SignUp/SignUpForm.tsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,18 @@
import React, { Dispatch } from 'react';
import { FormProvider, useForm } from 'react-hook-form';
import { joiResolver } from '@hookform/resolvers/joi';
import { useQuery } from '@tanstack/react-query';
import { useSetRecoilState } from 'recoil';

import { checkUserExists, checkUserExistsAD } from '@/api/authService';
import Button from '@/components/Primitives/Inputs/Button/Button';
import Input from '@/components/Primitives/Inputs/Input/Input';
import Text from '@/components/Primitives/Text/Text';
import { NEXT_PUBLIC_ENABLE_AZURE } from '@/constants';
import { createErrorMessage } from '@/constants/toasts';
import { SignUpEnum } from '@/enums/auth/signUp';
import { ToastStateEnum } from '@/enums/toasts/toast-types';
import SchemaEmail from '@/schema/schemaEmail';
import { toastState } from '@/store/toast/atom/toast.atom';
import { FlexForm } from '@/styles/pages/pages.styles';
import { EmailUser } from '@/types/user/user';
import useSignUp from '@hooks/auth/useSignUp';

interface SignUpFormProps {
setShowSignUp: Dispatch<React.SetStateAction<SignUpEnum>>;
Expand All @@ -32,46 +30,31 @@ const SignUpForm = ({ setShowSignUp, setEmailName, emailName }: SignUpFormProps)
},
resolver: joiResolver(SchemaEmail),
});
useQuery(
['checkUserExists', emailName],
() =>
NEXT_PUBLIC_ENABLE_AZURE
? checkUserExistsAD(emailName.email)
: checkUserExists(emailName.email),
{
enabled: !!emailName.email && !emailName.goback,
suspense: false,
onSuccess: (data) => {
if (data === 'az') {
setShowSignUp(SignUpEnum.SIGN_UP_OPTIONS);
return;
}

if (!data) {
setShowSignUp(SignUpEnum.REGISTER);
return;
}
useSignUp(emailName, {
onSuccess: (data) => {
if (data === 'az') {
setShowSignUp(SignUpEnum.SIGN_UP_OPTIONS);
return;
}

methods.setError('email', { type: 'custom', message: 'This email already exists' });
},
if (!data) {
setShowSignUp(SignUpEnum.REGISTER);
return;
}

onError: (error: Error) => {
/**
* When checkUserExistsAD returns 404, allow manual sign up
*/
if (error.message.includes('404')) {
setShowSignUp(SignUpEnum.REGISTER);
return;
}

setToastState({
open: true,
type: ToastStateEnum.ERROR,
content: 'Connection error, please try again',
});
},
methods.setError('email', { type: 'custom', message: 'This email already exists!' });
},
);
onError: (error: Error) => {
/**
* When checkUserExistsAD returns 404, allow manual sign up
*/
if (error.message.includes('404')) {
setShowSignUp(SignUpEnum.REGISTER);
return;
}
},
});

const handleCheckUserExists = async (email: string) => {
setEmailName({ goback: false, email });
Expand All @@ -83,11 +66,7 @@ const SignUpForm = ({ setShowSignUp, setEmailName, emailName }: SignUpFormProps)
direction="column"
onSubmit={methods.handleSubmit(({ email }) => {
if (!email) {
setToastState({
open: true,
type: ToastStateEnum.ERROR,
content: 'Network error, please try again ',
});
setToastState(createErrorMessage('Network error, please try again!'));
return;
}
handleCheckUserExists(email);
Expand Down
Loading

0 comments on commit 4a7ac92

Please sign in to comment.