Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replaced use axios with use query on GeneralIntoStep container #3134

Open
wants to merge 6 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/constants/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export const URLs = {
},
users: {
get: '/users',
getUserById: '/users/:id',
update: '/users',
delete: '/users/delete',
deactivate: '/users/deactivate',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
import { validations } from '~/components/user-steps-wrapper/constants'
import { styles } from '~/containers/tutor-home-page/general-info-step/GeneralInfoStep.styles'
import { useStepContext } from '~/context/step-context'
import useAxios from '~/hooks/use-axios'
import useQuery from '~/hooks/use-query'
import useBreakpoints from '~/hooks/use-breakpoints'
import useForm from '~/hooks/use-form'
import { useAppSelector } from '~/hooks/use-redux'
Expand All @@ -20,17 +20,11 @@

interface GeneralInfoStepProps {
btnsBox: ReactNode
isUserFetched: boolean
setIsUserFetched: (isUserFetched: boolean) => void
}

type UserName = { firstName: string; lastName: string }

const GeneralInfoStep = ({
btnsBox,
isUserFetched,
setIsUserFetched
}: GeneralInfoStepProps) => {
const GeneralInfoStep = ({ btnsBox }: GeneralInfoStepProps) => {
const { t } = useTranslation()
const { isLaptopAndAbove, isMobile } = useBreakpoints()
const { stepData, handleGeneralInfo } = useStepContext()
Expand All @@ -56,31 +50,31 @@
})

const getUserById = useCallback(
() => userService.getUserById(userId, userRole as UserRole),
() => userService.getUserByIdWithBaseService(userId, userRole as UserRole),
[userId, userRole]
)

const updateUserName = useCallback(
(user: UserName) => {
handleNonInputValueChange('firstName', user.firstName)
handleNonInputValueChange('lastName', user.lastName)

setIsUserFetched(true)
},
[handleNonInputValueChange, setIsUserFetched]
[handleNonInputValueChange]
)

const { loading: userLoading, fetchData: fetchUser } = useAxios({
service: getUserById,
defaultResponse: { firstName: '', lastName: '' },
fetchOnMount: false,
onResponse: updateUserName
const { isLoading: userLoading, data: userResponse } = useQuery({
queryFn: getUserById,
queryKey: ['user', userId],
options: {
staleTime: Infinity
}
})

useEffect(() => {
!isUserFetched && void fetchUser()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
if (userResponse) {
updateUserName(userResponse)
}
}, [userResponse])

Check warning on line 77 in src/containers/tutor-home-page/general-info-step/GeneralInfoStep.tsx

View workflow job for this annotation

GitHub Actions / lint

React Hook useEffect has a missing dependency: 'updateUserName'. Either include it or remove the dependency array
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need to discuss problems with useForm hook on our next daily call, remind me please about it


useEffect(() => {
handleGeneralInfo({ data, errors })
Expand Down
14 changes: 13 additions & 1 deletion src/services/course-service.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { AxiosResponse } from 'axios'
import { URLs } from '~/constants/request'
import { axiosClient } from '~/plugins/axiosClient'
import { Course, CourseForm, GetCoursesParams } from '~/types'
import { Course, CourseForm, GetCoursesParams, ItemsWithCount } from '~/types'
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
import { Course, CourseForm, GetCoursesParams, ItemsWithCount } from '~/types'
import type { Course, CourseForm, GetCoursesParams, ItemsWithCount } from '~/types'

import { createUrlPath } from '~/utils/helper-functions'
import { getFullUrl } from '~/utils/get-full-url'
import { baseService } from './base-service'

export interface Resource {
_id: string
Expand All @@ -23,6 +25,16 @@ export interface ResourceData {
export const CourseService = {
getCourses: async (params?: GetCoursesParams): Promise<AxiosResponse> =>
await axiosClient.get(URLs.courses.get, { params }),

getCoursesWithBaseService: (params?: GetCoursesParams) => {
return baseService.request<ItemsWithCount<Course>>({
method: 'GET',
url: getFullUrl({
pathname: URLs.courses.get,
searchParameters: params
})
})
},
addCourse: async (data?: CourseForm): Promise<AxiosResponse> =>
await axiosClient.post(URLs.courses.create, data),
getCourse: async (id?: string): Promise<AxiosResponse<Course>> =>
Expand Down
20 changes: 20 additions & 0 deletions src/services/user-service.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { AxiosResponse } from 'axios'
import { axiosClient } from '~/plugins/axiosClient'
import { URLs } from '~/constants/request'
import { createUrlPath } from '~/utils/helper-functions'
import { getFullUrl } from '~/utils/get-full-url'
import { baseService } from './base-service'
import {
GetUsersParams,
UpdateUserParams,
Expand All @@ -25,6 +27,24 @@ export const userService = {
createUrlPath(URLs.users.get, userId, { role: userRole, isEdit })
)
},

getUserByIdWithBaseService: (
id: string,
userRole: UserRole,
isEdit?: boolean
) => {
return baseService.request<UserResponse>({
method: 'GET',
url: getFullUrl({
pathname: URLs.users.getUserById,
parameters: { id },
searchParameters: {
role: userRole,
isEdit: isEdit !== undefined ? isEdit.toString() : undefined
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I saw the same in one of your previous PRs, did I missed something?

Suggested change
isEdit: isEdit !== undefined ? isEdit.toString() : undefined
isEdit: isEdit?.toString() ?? undefined

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes, I forgot to fix it in this PR too, but I'll first merge the previous PR and then do a rebase

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You need to rebase your other branch and then do rebase on this branch. Don't use merge, please

}
})
})
},
updateUser: (
userId: string,
params: UpdateUserParams
Expand Down
2 changes: 1 addition & 1 deletion src/types/course/interfaces/course.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export interface CourseFilters extends Pick<Course, 'proficiencyLevel'> {
page?: string | number
}

export interface GetCoursesParams extends Partial<RequestParams> {
export type GetCoursesParams = Partial<RequestParams> & {
title?: string
fileName?: string
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ describe('UserStepsWrapper test', () => {
})
})

it('should render first tab', () => {
const firstTab = screen.getByText(/becomeTutor.generalInfo.title/i)
it('should render first tab', async () => {
const firstTab = await screen.findByText(/becomeTutor.generalInfo.title/i)

expect(firstTab).toBeInTheDocument()
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ describe('GeneralInfoStep test', () => {
beforeEach(async () => {
await waitFor(() => {
mockAxiosClient
.onGet(`${URLs.users.get}/${userId}?role=${userRole}`)
.onGet(new RegExp(URLs.users.getUserById.replace(':id', userId)))
.reply(200, userDataMock)
mockAxiosClient
.onGet(URLs.location.getCountries)
Expand Down Expand Up @@ -67,14 +67,13 @@ describe('GeneralInfoStep test', () => {
})
})

it('should change firstName input', () => {
const firstNameInput = screen.getByLabelText(/common.labels.firstName/i)

act(() => {
fireEvent.change(firstNameInput, { target: { value: 'testName' } })
})

expect(firstNameInput.value).toBe('testName')
it('should change firstName input', async () => {
const firstNameInput = await screen.findByLabelText(/common.labels.firstName/i)
act(() => {
fireEvent.change(firstNameInput, { target: { value: 'testName' } })
})

expect(firstNameInput.value).toBe('testName')
})

it('should choose option in countries autocomplete', () => {
Expand Down
11 changes: 10 additions & 1 deletion tests/unit/pages/student-home/StudentHome.spec.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ import { screen, waitFor } from '@testing-library/react'

import StudentHome from '~/pages/student-home/StudentHome'

import { renderWithProviders } from '~tests/test-utils'
import { renderWithProviders, mockAxiosClient } from '~tests/test-utils'
import { URLs } from '~/constants/request'
import { beforeAll } from 'vitest'

const userId = '63f5d0ebb'

Expand All @@ -13,7 +15,14 @@ const secondLoginState = {
appMain: { isFirstLogin: false, userRole: 'student', userId }
}

const userDataMock = { _id: userId, firstName: 'test', lastName: 'test' }

describe('StudentsHome component', () => {
beforeAll( async () => {
mockAxiosClient
.onGet(new RegExp(URLs.users.getUserById.replace(':id', userId)))
.reply(200, userDataMock)
})
it('should render modal when logging in for the first time', async () => {
renderWithProviders(<StudentHome />, {
preloadedState: firstLoginState
Expand Down
Loading