From 4a7ac92d60078106eb994379a3619d546ffad4a0 Mon Sep 17 00:00:00 2001 From: Guido Pereira Date: Fri, 21 Apr 2023 15:11:54 +0100 Subject: [PATCH] refactor: react query status on useeffect & toast messages (#1423) Co-authored-by: JoaoSaIvador --- .../components/Board/DragDropArea/index.tsx | 8 +- .../MyBoards/ListBoardsByTeam/index.tsx | 8 +- .../MyBoards/ListPersonalBoards/index.tsx | 8 +- .../ListParticipants/ListParticipants.tsx | 8 +- .../SettingsTabs/SettingsTabs.tsx | 10 +- .../SplitBoard/SettingsTabs/SettingsTabs.tsx | 10 +- .../Dashboard/RecentRetros/index.tsx | 8 +- .../Teams/CreateTeam/CreateTeam.spec.tsx | 3 +- .../Teams/CreateTeam/CreateTeam.tsx | 26 ++--- .../Teams/Team/ListMembers/ListMembers.tsx | 8 +- .../src/components/auth/LoginForm/index.tsx | 8 +- .../components/auth/SignUp/RegisterForm.tsx | 8 +- .../src/components/auth/SignUp/SignUpForm.tsx | 69 ++++-------- frontend/src/hooks/auth/useSignUp.tsx | 42 +++++++ frontend/src/hooks/useSocketIO.ts | 8 +- .../pages/boards/[boardId]/participants.tsx | 26 +---- frontend/src/pages/boards/newRegularBoard.tsx | 106 +++++++++--------- frontend/src/pages/boards/newSplitBoard.tsx | 55 +++++---- 18 files changed, 190 insertions(+), 229 deletions(-) create mode 100644 frontend/src/hooks/auth/useSignUp.tsx diff --git a/frontend/src/components/Board/DragDropArea/index.tsx b/frontend/src/components/Board/DragDropArea/index.tsx index 539098992..11f3ad058 100644 --- a/frontend/src/components/Board/DragDropArea/index.tsx +++ b/frontend/src/components/Board/DragDropArea/index.tsx @@ -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'; @@ -94,11 +94,7 @@ const DragDropArea: React.FC = ({ 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.')); } }; diff --git a/frontend/src/components/Boards/MyBoards/ListBoardsByTeam/index.tsx b/frontend/src/components/Boards/MyBoards/ListBoardsByTeam/index.tsx index 5cd461a88..bca419830 100644 --- a/frontend/src/components/Boards/MyBoards/ListBoardsByTeam/index.tsx +++ b/frontend/src/components/Boards/MyBoards/ListBoardsByTeam/index.tsx @@ -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'; @@ -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')); }, }, ); diff --git a/frontend/src/components/Boards/MyBoards/ListPersonalBoards/index.tsx b/frontend/src/components/Boards/MyBoards/ListPersonalBoards/index.tsx index 2ba5dd081..85c1ee659 100644 --- a/frontend/src/components/Boards/MyBoards/ListPersonalBoards/index.tsx +++ b/frontend/src/components/Boards/MyBoards/ListPersonalBoards/index.tsx @@ -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'; @@ -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')); }, }, ); diff --git a/frontend/src/components/CreateBoard/RegularBoard/ParticipantsTab/ListParticipants/ListParticipants.tsx b/frontend/src/components/CreateBoard/RegularBoard/ParticipantsTab/ListParticipants/ListParticipants.tsx index c3f30763c..cab8793f1 100644 --- a/frontend/src/components/CreateBoard/RegularBoard/ParticipantsTab/ListParticipants/ListParticipants.tsx +++ b/frontend/src/components/CreateBoard/RegularBoard/ParticipantsTab/ListParticipants/ListParticipants.tsx @@ -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'; @@ -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); }; diff --git a/frontend/src/components/CreateBoard/RegularBoard/SettingsTabs/SettingsTabs.tsx b/frontend/src/components/CreateBoard/RegularBoard/SettingsTabs/SettingsTabs.tsx index af11c25ab..e3477d0fb 100644 --- a/frontend/src/components/CreateBoard/RegularBoard/SettingsTabs/SettingsTabs.tsx +++ b/frontend/src/components/CreateBoard/RegularBoard/SettingsTabs/SettingsTabs.tsx @@ -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, @@ -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]); diff --git a/frontend/src/components/CreateBoard/SplitBoard/SettingsTabs/SettingsTabs.tsx b/frontend/src/components/CreateBoard/SplitBoard/SettingsTabs/SettingsTabs.tsx index 1e5201b46..723cf4e50 100644 --- a/frontend/src/components/CreateBoard/SplitBoard/SettingsTabs/SettingsTabs.tsx +++ b/frontend/src/components/CreateBoard/SplitBoard/SettingsTabs/SettingsTabs.tsx @@ -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'; @@ -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]); diff --git a/frontend/src/components/Dashboard/RecentRetros/index.tsx b/frontend/src/components/Dashboard/RecentRetros/index.tsx index 826d92b24..614723747 100644 --- a/frontend/src/components/Dashboard/RecentRetros/index.tsx +++ b/frontend/src/components/Dashboard/RecentRetros/index.tsx @@ -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'; @@ -28,11 +28,7 @@ const RecentRetros = React.memo(({ userId }) => { return undefined; }, onError: () => { - setToastState({ - open: true, - content: 'Error getting the boards', - type: ToastStateEnum.ERROR, - }); + setToastState(createErrorMessage('Error getting the boards')); }, }, ); diff --git a/frontend/src/components/Teams/CreateTeam/CreateTeam.spec.tsx b/frontend/src/components/Teams/CreateTeam/CreateTeam.spec.tsx index 4538e20d8..2fb9a40c4 100644 --- a/frontend/src/components/Teams/CreateTeam/CreateTeam.spec.tsx +++ b/frontend/src/components/Teams/CreateTeam/CreateTeam.spec.tsx @@ -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()); }); }); diff --git a/frontend/src/components/Teams/CreateTeam/CreateTeam.tsx b/frontend/src/components/Teams/CreateTeam/CreateTeam.tsx index 826b330d1..926289de4 100644 --- a/frontend/src/components/Teams/CreateTeam/CreateTeam.tsx +++ b/frontend/src/components/Teams/CreateTeam/CreateTeam.tsx @@ -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'; @@ -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); @@ -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(); }; @@ -74,16 +84,6 @@ const CreateTeam = () => { setIsOpen(true); }; - useEffect(() => { - if (status === 'error') { - setDisableButtons(false); - } - - if (status === 'success') { - push(ROUTES.Teams); - } - }, [status]); - return ( { 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); diff --git a/frontend/src/components/auth/LoginForm/index.tsx b/frontend/src/components/auth/LoginForm/index.tsx index db6af7099..32d8ec781 100644 --- a/frontend/src/components/auth/LoginForm/index.tsx +++ b/frontend/src/components/auth/LoginForm/index.tsx @@ -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'; @@ -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 })); diff --git a/frontend/src/components/auth/SignUp/RegisterForm.tsx b/frontend/src/components/auth/SignUp/RegisterForm.tsx index 33b9a6d6e..6c62e9133 100644 --- a/frontend/src/components/auth/SignUp/RegisterForm.tsx +++ b/frontend/src/components/auth/SignUp/RegisterForm.tsx @@ -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'; @@ -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); diff --git a/frontend/src/components/auth/SignUp/SignUpForm.tsx b/frontend/src/components/auth/SignUp/SignUpForm.tsx index 297e3fd1c..cfb45faae 100644 --- a/frontend/src/components/auth/SignUp/SignUpForm.tsx +++ b/frontend/src/components/auth/SignUp/SignUpForm.tsx @@ -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>; @@ -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 }); @@ -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); diff --git a/frontend/src/hooks/auth/useSignUp.tsx b/frontend/src/hooks/auth/useSignUp.tsx new file mode 100644 index 000000000..032ca017c --- /dev/null +++ b/frontend/src/hooks/auth/useSignUp.tsx @@ -0,0 +1,42 @@ +import { useQuery } from '@tanstack/react-query'; +import { useSetRecoilState } from 'recoil'; + +import { NEXT_PUBLIC_ENABLE_AZURE } from '@/constants'; +import { createErrorMessage } from '@/constants/toasts'; +import { toastState } from '@/store/toast/atom/toast.atom'; +import { checkUserExists, checkUserExistsAD } from '@api/authService'; + +type EmailNameType = { + email: string; + goback: boolean; +}; + +type UseSignUpCallback = { + onSuccess: (data: boolean | 'az' | 'local') => void; + onError: (error: Error) => void; +}; + +const useSignUp = (emailName: EmailNameType, { onSuccess, onError }: UseSignUpCallback) => { + const setToastState = useSetRecoilState(toastState); + + return useQuery( + ['checkUserExists', emailName.email], + () => { + NEXT_PUBLIC_ENABLE_AZURE + ? checkUserExistsAD(emailName.email) + : checkUserExists(emailName.email); + }, + { + enabled: !!emailName.email && !emailName.goback, + refetchOnMount: false, + refetchOnWindowFocus: false, + onSuccess, + onError: (error: Error) => { + onError(error); + setToastState(createErrorMessage('Connection error, please try again!')); + }, + }, + ); +}; + +export default useSignUp; diff --git a/frontend/src/hooks/useSocketIO.ts b/frontend/src/hooks/useSocketIO.ts index c8888194a..a19b58bbc 100644 --- a/frontend/src/hooks/useSocketIO.ts +++ b/frontend/src/hooks/useSocketIO.ts @@ -6,8 +6,8 @@ import { io, Socket } from 'socket.io-client'; import { BOARD_PHASE_SERVER_SENT, NEXT_PUBLIC_BACKEND_URL } from '@/constants'; import { ROUTES } from '@/constants/routes'; +import { createErrorMessage } from '@/constants/toasts'; import { BoardAction } from '@/enums/boards/actions'; -import { ToastStateEnum } from '@/enums/toasts/toast-types'; import useBoard from '@/hooks/useBoard'; import useCards from '@/hooks/useCards'; import useComments from '@/hooks/useComments'; @@ -82,11 +82,7 @@ export const useSocketIO = (boardId: string): SocketInterface => { socket?.on('deleteBoard', () => { router.replace(ROUTES.Boards); - setToastState({ - open: true, - content: 'The board was deleted by a board admin.', - type: ToastStateEnum.ERROR, - }); + setToastState(createErrorMessage('The board was deleted by a board admin.')); }); socket?.on('board', (board: BoardType) => { diff --git a/frontend/src/pages/boards/[boardId]/participants.tsx b/frontend/src/pages/boards/[boardId]/participants.tsx index 2187a8604..5aa323303 100644 --- a/frontend/src/pages/boards/[boardId]/participants.tsx +++ b/frontend/src/pages/boards/[boardId]/participants.tsx @@ -1,6 +1,6 @@ import React, { Suspense, useCallback, useEffect } from 'react'; import { GetServerSideProps } from 'next'; -import { dehydrate, QueryClient, useQuery } from '@tanstack/react-query'; +import { dehydrate, QueryClient } from '@tanstack/react-query'; import { SetterOrUpdater, useRecoilState, useSetRecoilState } from 'recoil'; import { getBoardRequest } from '@/api/boardService'; @@ -10,15 +10,15 @@ import RegularBoardHeader from '@/components/Board/RegularBoard/RegularHeader'; import QueryError from '@/components/Errors/QueryError'; import Flex from '@/components/Primitives/Layout/Flex/Flex'; import LoadingPage from '@/components/Primitives/Loading/Page/Page'; +import { USERS_KEY } from '@/constants/react-query/keys'; import { DASHBOARD_ROUTE } from '@/constants/routes'; import { BoardUserRoles } from '@/enums/boards/userRoles'; -import { ToastStateEnum } from '@/enums/toasts/toast-types'; import useBoard from '@/hooks/useBoard'; import { boardInfoState, boardParticipantsState } from '@/store/board/atoms/board.atom'; -import { toastState } from '@/store/toast/atom/toast.atom'; import { usersListState } from '@/store/user.atom'; import { BoardUser } from '@/types/board/board.user'; import { UserList } from '@/types/team/userList'; +import useUsers from '@hooks/users/useUsers'; // Sorts participants list to show responsibles first and then regular board members export const sortParticipantsList = ( @@ -41,7 +41,6 @@ export const sortParticipantsList = ( }; const BoardParticipants = () => { - const setToastState = useSetRecoilState(toastState); const [boardParticipants, setBoardParticipants] = useRecoilState(boardParticipantsState); const [recoilBoard, setRecoilBoard] = useRecoilState(boardInfoState); @@ -59,17 +58,7 @@ const BoardParticipants = () => { } }, [boardData, setBoardParticipants, setRecoilBoard]); - const usersData = useQuery(['users'], () => getAllUsers(), { - enabled: true, - refetchOnWindowFocus: false, - onError: () => { - setToastState({ - open: true, - content: 'Error getting the users', - type: ToastStateEnum.ERROR, - }); - }, - }).data; + const { data: usersData } = useUsers(); const setUsersListState = useSetRecoilState(usersListState); @@ -109,17 +98,12 @@ const BoardParticipants = () => { export const getServerSideProps: GetServerSideProps = async (context) => { const boardId = String(context.query.boardId); - if (boardId.includes('.map')) - return { - props: {}, - }; - const queryClient = new QueryClient(); try { await queryClient.fetchQuery(['board', { id: boardId }], () => getBoardRequest(boardId, context), ); - await queryClient.prefetchQuery(['users'], () => getAllUsers(context)); + await queryClient.prefetchQuery([USERS_KEY], () => getAllUsers(context)); } catch (e) { return { redirect: { diff --git a/frontend/src/pages/boards/newRegularBoard.tsx b/frontend/src/pages/boards/newRegularBoard.tsx index 56df8e053..131dbc961 100644 --- a/frontend/src/pages/boards/newRegularBoard.tsx +++ b/frontend/src/pages/boards/newRegularBoard.tsx @@ -4,7 +4,7 @@ import { GetServerSideProps, GetServerSidePropsContext, NextPage } from 'next'; import { useRouter } from 'next/router'; import { getSession } from 'next-auth/react'; import { joiResolver } from '@hookform/resolvers/joi'; -import { dehydrate, QueryClient, useQuery } from '@tanstack/react-query'; +import { dehydrate, QueryClient } from '@tanstack/react-query'; import { useRecoilState, useSetRecoilState } from 'recoil'; import { getAllTeams, getUserTeams } from '@/api/teamService'; @@ -20,11 +20,11 @@ import Flex from '@/components/Primitives/Layout/Flex/Flex'; import TipBar from '@/components/Primitives/Layout/TipBar/TipBar'; import LoadingPage from '@/components/Primitives/Loading/Page/Page'; import { defaultRegularColumns } from '@/constants/boards/defaultColumns'; -import { TEAMS_KEY } from '@/constants/react-query/keys'; -import { DASHBOARD_ROUTE } from '@/constants/routes'; +import { TEAMS_KEY, USERS_KEY } from '@/constants/react-query/keys'; +import { DASHBOARD_ROUTE, ROUTES } from '@/constants/routes'; import REGULAR_BOARD_TIPS from '@/constants/tips/regularBoard'; +import { createSuccessMessage } from '@/constants/toasts'; import { BoardUserRoles } from '@/enums/boards/userRoles'; -import { ToastStateEnum } from '@/enums/toasts/toast-types'; import useTeams from '@/hooks/teams/useTeams'; import useBoard from '@/hooks/useBoard'; import useCurrentSession from '@/hooks/useCurrentSession'; @@ -35,6 +35,7 @@ import { usersListState } from '@/store/user.atom'; import { StyledForm } from '@/styles/pages/pages.styles'; import { BoardUser, BoardUserDto } from '@/types/board/board.user'; import isEmpty from '@/utils/isEmpty'; +import useUsers from '@hooks/users/useUsers'; const defaultBoard = { users: [], @@ -78,17 +79,8 @@ const NewRegularBoard: NextPage = () => { // Team Hook const { data: userBasedTeams } = useTeams(isSAdmin); - const { data: allUsers } = useQuery(['users'], () => getAllUsers(), { - enabled: true, - refetchOnWindowFocus: false, - onError: () => { - setToastState({ - open: true, - content: 'Error getting the users', - type: ToastStateEnum.ERROR, - }); - }, - }); + // User Hook + const { data: allUsers } = useUsers(); useEffect(() => { if (allUsers) { @@ -103,7 +95,7 @@ const NewRegularBoard: NextPage = () => { // Board Hook const { - createBoard: { status, mutate }, + createBoard: { mutate }, } = useBoard({ autoFetchBoard: false }); const addNewRegularBoard = () => { @@ -151,6 +143,15 @@ const NewRegularBoard: NextPage = () => { return []; }); + const onMutateSuccess = () => { + setIsPageLoading(true); + setToastState(createSuccessMessage('Board created with success!')); + + setBoardState(defaultBoard); + setSelectedTeam(undefined); + router.push(ROUTES.Boards); + }; + const saveBoard = (title?: string, maxVotes?: number, slackEnable?: boolean) => { const users: BoardUserDto[] = []; @@ -171,19 +172,24 @@ const NewRegularBoard: NextPage = () => { }); } - mutate({ - ...boardState.board, - columns: defaultRegularColumns, - users, - title: title || defaultBoard.board.title, - dividedBoards: [], - maxVotes, - slackEnable, - maxUsers: boardState.count.maxUsersCount, - recurrent: false, - responsibles, - phase: undefined, - }); + mutate( + { + ...boardState.board, + columns: defaultRegularColumns, + users, + title: title || defaultBoard.board.title, + dividedBoards: [], + maxVotes, + slackEnable, + maxUsers: boardState.count.maxUsersCount, + recurrent: false, + responsibles, + phase: undefined, + }, + { + onSuccess: onMutateSuccess, + }, + ); }; const saveEmptyBoard = () => { @@ -192,39 +198,31 @@ const NewRegularBoard: NextPage = () => { users.push({ role: BoardUserRoles.RESPONSIBLE, user: userId }); } - mutate({ - ...boardState.board, - columns: defaultRegularColumns, - users, - title: defaultBoard.board.title, - dividedBoards: [], - maxUsers: boardState.count.maxUsersCount, - recurrent: false, - responsibles: [userId], - }); + mutate( + { + ...boardState.board, + columns: defaultRegularColumns, + users, + title: defaultBoard.board.title, + dividedBoards: [], + maxUsers: boardState.count.maxUsersCount, + recurrent: false, + responsibles: [userId], + }, + { + onSuccess: onMutateSuccess, + }, + ); }; const hasResponsibles = !isEmpty(filterResponsibles(boardState.users)); useEffect(() => { - if (status === 'success') { - setIsPageLoading(true); - setToastState({ - open: true, - content: 'Board created with success!', - type: ToastStateEnum.SUCCESS, - }); - - setBoardState(defaultBoard); - setSelectedTeam(undefined); - router.push('/boards'); - } - return () => { setBoardState(defaultBoard); setSelectedTeam(undefined); }; - }, [router, setToastState, setSelectedTeam, setBoardState, status]); + }, [setSelectedTeam, setBoardState]); if (!session || !userBasedTeams) return null; @@ -320,7 +318,7 @@ export const getServerSideProps: GetServerSideProps = requireAuthentication( } return getUserTeams(userId, context); }), - queryClient.prefetchQuery(['users'], () => getAllUsers(context)), + queryClient.prefetchQuery([USERS_KEY], () => getAllUsers(context)), ]); return { diff --git a/frontend/src/pages/boards/newSplitBoard.tsx b/frontend/src/pages/boards/newSplitBoard.tsx index e73f506fb..424153020 100644 --- a/frontend/src/pages/boards/newSplitBoard.tsx +++ b/frontend/src/pages/boards/newSplitBoard.tsx @@ -24,9 +24,9 @@ import { defaultSplitColumns } from '@/constants/boards/defaultColumns'; import { TEAMS_KEY } from '@/constants/react-query/keys'; import { DASHBOARD_ROUTE, ROUTES } from '@/constants/routes'; import SPLIT_BOARD_TIPS from '@/constants/tips/splitBoard'; +import { createSuccessMessage } from '@/constants/toasts'; import { BoardPhases } from '@/enums/boards/phases'; import { BoardUserRoles } from '@/enums/boards/userRoles'; -import { ToastStateEnum } from '@/enums/toasts/toast-types'; import useTeams from '@/hooks/teams/useTeams'; import useBoard from '@/hooks/useBoard'; import useCurrentSession from '@/hooks/useCurrentSession'; @@ -84,7 +84,7 @@ const NewSplitBoard: NextPage = () => { // User Board Hook const { - createBoard: { status, mutate }, + createBoard: { mutate }, } = useBoard({ autoFetchBoard: false }); // Team Hook @@ -169,40 +169,39 @@ const NewSplitBoard: NextPage = () => { role: boardUser.role, })); - mutate({ - ...boardState.board, - users: boardUsersDtos, - title, - dividedBoards: newDividedBoards, - maxVotes, - maxUsers, - team, - responsibles, - slackEnable, - phase: BoardPhases.ADDCARDS, - }); + mutate( + { + ...boardState.board, + users: boardUsersDtos, + title, + dividedBoards: newDividedBoards, + maxVotes, + maxUsers, + team, + responsibles, + slackEnable, + phase: BoardPhases.ADDCARDS, + }, + { + onSuccess: () => { + setIsLoading(true); + setToastState(createSuccessMessage('Board created with success!')); + + setBoardState(defaultBoard); + setSelectedTeam(undefined); + router.push(ROUTES.Boards); + }, + }, + ); }; useEffect(() => { - if (status === 'success') { - setIsLoading(true); - setToastState({ - open: true, - content: 'Board created with success!', - type: ToastStateEnum.SUCCESS, - }); - - setBoardState(defaultBoard); - setSelectedTeam(undefined); - router.push('/boards'); - } - return () => { setBoardState(defaultBoard); setSelectedTeam(undefined); setHaveError(false); }; - }, [status, router, setToastState, setSelectedTeam, setBoardState, setHaveError]); + }, [setSelectedTeam, setBoardState, setHaveError]); if (!session || !userBasedTeams) return null;