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 useAxios with useQuery and useMutation hooks on CategoryDropdown container #3102

Merged
Merged
Show file tree
Hide file tree
Changes from 24 commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
d99f926
added useQuery and useMutation hooks t CategoryDropdown page
amoutens Jan 15, 2025
1200f8f
changed occurrence files that also have service functions from Catego…
amoutens Jan 15, 2025
7ca925a
fixed tests
amoutens Jan 15, 2025
4bd61be
added useQuery and useMutation hooks t CategoryDropdown page
amoutens Jan 15, 2025
784aac3
changed occurrence files that also have service functions from Catego…
amoutens Jan 15, 2025
3ac02d5
fixed tests
amoutens Jan 15, 2025
f40b941
Merge branch 'feature/3074/replace-useAxios-with-useQuery-categoryDro…
amoutens Jan 15, 2025
03a1784
added more tests
amoutens Jan 15, 2025
ad1607f
removed promise from callback
amoutens Jan 16, 2025
cb9c08c
fixed service in mutation and fixed tests
amoutens Jan 16, 2025
e58937b
fixed tests
amoutens Jan 16, 2025
9351e30
added useQuery and useMutation hooks t CategoryDropdown page
amoutens Jan 15, 2025
6460ec5
changed occurrence files that also have service functions from Catego…
amoutens Jan 15, 2025
57bcecb
fixed tests
amoutens Jan 15, 2025
10f21a4
added useQuery and useMutation hooks t CategoryDropdown page
amoutens Jan 15, 2025
cb10ace
changed occurrence files that also have service functions from Catego…
amoutens Jan 15, 2025
253f3e3
added more tests
amoutens Jan 15, 2025
fdae645
removed promise from callback
amoutens Jan 16, 2025
b8e44a6
fixed service in mutation and fixed tests
amoutens Jan 16, 2025
7eb39d2
fixed tests
amoutens Jan 16, 2025
201f9c3
Merge branch 'feature/3074/replace-useAxios-with-useQuery-categoryDro…
amoutens Jan 17, 2025
d5bddb4
fixed tests after rebase
amoutens Jan 17, 2025
ae221b9
fixed comments
amoutens Jan 17, 2025
9c345d0
fixed comments
amoutens Jan 17, 2025
385c3c5
fixed comments
amoutens Jan 22, 2025
a07adda
Merge branch 'develop' into feature/3074/replace-useAxios-with-useQue…
amoutens Jan 22, 2025
d064c9e
fixed tests
amoutens Jan 22, 2025
6c2ee49
Merge branch 'develop' into feature/3074/replace-useAxios-with-useQue…
amoutens Jan 24, 2025
b94ee3f
fixed comments
amoutens Jan 24, 2025
7a8256e
fixed comments
amoutens Jan 29, 2025
d3dd349
added type to import
amoutens Jan 29, 2025
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
18 changes: 10 additions & 8 deletions src/components/app-button-menu/AppButtonMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,25 +10,24 @@ import ErrorOutlineIcon from '@mui/icons-material/ErrorOutline'
import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown'
import CircleIcon from '@mui/icons-material/Circle'

import useAxios from '~/hooks/use-axios'
import useQuery from '~/hooks/use-query'
import useMenu from '~/hooks/use-menu'
import Loader from '~/components/loader/Loader'
import AppButton from '~/components/app-button/AppButton'
import AppMenuButton from '~/components/app-menu-button/AppMenuButton'
import AppSelectButton from '~/components/app-select-button/AppSelectButton'

import { defaultResponses } from '~/constants'
import { spliceSx } from '~/utils/helper-functions'
import { styles } from '~/components/app-button-menu/AppButtonMenu.styles'
import {
ButtonVariantEnum,
CategoryNameInterface,
ServiceFunction
ServiceFunctionNew
} from '~/types'

interface AppButtonMenuProps<T> extends Omit<MenuProps, 'open'> {
title: string
service: ServiceFunction<T[]>
service: ServiceFunctionNew<T[]>
selectedItems: string[]
setSelectedItems: (value: string[]) => void
position?: PopoverOrigin['horizontal']
Expand Down Expand Up @@ -65,12 +64,15 @@ const AppButtonMenu = <T extends Pick<CategoryNameInterface, '_id'>>({
setSelectedItems([])
}

const { loading, response } = useAxios<T[]>({
service,
defaultResponse: defaultResponses.array
const { data: response, isLoading } = useQuery({
queryKey: [title],
ShadowOfTheSpace marked this conversation as resolved.
Show resolved Hide resolved
queryFn: service
})

const filteredItems = useMemo(() => {
if (!response) {
return []
}
const noneItem = {
_id: 'null',
[valueField as string]: 'No category'
Expand Down Expand Up @@ -115,7 +117,7 @@ const AppButtonMenu = <T extends Pick<CategoryNameInterface, '_id'>>({
</Box>
)

const itemsLoad = !response.length && loading
const itemsLoad = !response || isLoading
const chosenFiltersText = selectedNames.length
? selectedNames.join(', ')
: t('cooperationsPage.tabs.all')
Expand Down
56 changes: 24 additions & 32 deletions src/containers/category-dropdown/CategoryDropdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@ import Box from '@mui/material/Box'
import Divider from '@mui/material/Divider'
import AddIcon from '@mui/icons-material/Add'

import useAxios from '~/hooks/use-axios'
import { useModalContext } from '~/context/modal-context'
import { useAppDispatch } from '~/hooks/use-redux'
import useQuery from '~/hooks/use-query'
import useMutation from '~/hooks/use-mutation'
import { ResourceService } from '~/services/resource-service'
import AddCategoriesModal from '~/containers/my-resources/add-categories-modal/AddCategoriesModal'
import DropdownButton from '~/components/dropdown-add-btn/DropdownButton'
Expand All @@ -16,7 +17,6 @@ import {
Categories,
CategoryNameInterface,
ComponentEnum,
CreateCategoriesParams,
ErrorResponse
} from '~/types'
import { styles } from '~/containers/category-dropdown/CategoryDropdown.styles'
Expand Down Expand Up @@ -44,21 +44,22 @@ const CategoryDropdown = ({
const dispatch = useAppDispatch()
const { openModal, closeModal } = useModalContext()

const handleResponseError = (error?: ErrorResponse) => {
dispatch(
openAlert({
severity: snackbarVariants.error,
message: getErrorKey(error)
})
)
}
const handleResponseError = useCallback(
(error?: ErrorResponse) => {
ShadowOfTheSpace marked this conversation as resolved.
Show resolved Hide resolved
dispatch(
openAlert({
severity: snackbarVariants.error,
message: getErrorKey(error)
})
)
},
[dispatch]
)

const { response: allCategoriesNames, fetchData: fetchAllCategoriesNames } =
useAxios<CategoryNameInterface[]>({
service: ResourceService.getResourcesCategoriesNames,
defaultResponse: [],
fetchOnMount: true
})
const { data: allCategoriesNames = [] } = useQuery({
queryKey: ['categoriesNames'],
queryFn: ResourceService.getResourcesCategoriesName
})

const onCreateCategory = () => {
openModal({
Expand All @@ -72,14 +73,8 @@ const CategoryDropdown = ({
})
}

const createCategory = useCallback(
(params?: CreateCategoriesParams) =>
ResourceService.createResourceCategory(params),
[]
)

const onResponseCategory = useCallback(
async (response: Categories | null) => {
(response: Categories | null) => {
ShadowOfTheSpace marked this conversation as resolved.
Show resolved Hide resolved
const categoryName = response ? response.name : ''

dispatch(
Expand All @@ -93,18 +88,15 @@ const CategoryDropdown = ({
}
})
)

await fetchAllCategoriesNames()
},
[dispatch, fetchAllCategoriesNames]
[dispatch]
)

const { fetchData: handleCreateCategory } = useAxios({
service: createCategory,
defaultResponse: null,
fetchOnMount: false,
onResponse: onResponseCategory,
onResponseError: handleResponseError
const { mutate: handleCreateCategory } = useMutation({
queryKey: ['categoriesNames'],
mutationFn: ResourceService.createResourceCategory,
onSuccess: onResponseCategory,
onError: handleResponseError
})

const optionsList = (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import {

interface AddCategoriesModalProps {
closeModal: () => void
createCategories: (params?: CreateCategoriesParams) => Promise<void>
createCategories: (params: CreateCategoriesParams) => void
existingCategoriesNames: string[]
}

Expand All @@ -37,9 +37,9 @@ const AddCategoriesModal: FC<AddCategoriesModalProps> = ({
useForm<CreateCategoriesParams>({
initialValues: initialValues,
validations: validations(existingCategoriesNames),
onSubmit: async () => {
onSubmit: () => {
setLoading(true)
await createCategories({ name: data.name.trim() })
createCategories({ name: data.name.trim() })
setLoading(false)
closeModal()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ const AddResourceModal = <T extends TableItem>({
/>
<AppButtonMenu<CategoryNameInterface>
selectedItems={selectedItems}
service={ResourceService.getResourcesCategoriesNames}
service={ResourceService.getResourcesCategoriesName}
setSelectedItems={setSelectedItems}
showNoneProperty
title={t('myResourcesPage.categories.category')}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ const AddResourceWithInput: FC<AddResourceWithInputProps> = ({
}}
position={PositionEnum.Right}
selectedItems={selectedItems}
service={ResourceService.getResourcesCategoriesNames}
service={ResourceService.getResourcesCategoriesName}
setSelectedItems={setItems}
showNoneProperty
title={t('myResourcesPage.categories.category')}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import {
} from '~/services/resource-service'
import MyResourcesTable from '~/containers/my-resources/my-resources-table/MyResourcesTable'
import useAxios from '~/hooks/use-axios'
import useMutation from '~/hooks/use-mutation'
import useQuery from '~/hooks/use-query'
import useSort from '~/hooks/table/use-sort'
import useBreakpoints from '~/hooks/use-breakpoints'
import usePagination from '~/hooks/table/use-pagination'
Expand All @@ -31,9 +33,7 @@ import {
ItemsWithCount,
GetResourcesCategoriesParams,
ErrorResponse,
ResourcesTabsEnum,
CreateCategoriesParams,
CategoryNameInterface
ResourcesTabsEnum
} from '~/types'
import { adjustColumns, getScreenBasedLimit } from '~/utils/helper-functions'

Expand Down Expand Up @@ -98,12 +98,6 @@ const CategoriesContainer = () => {
[page, itemsPerPage, sort, searchTitle]
)

const createCategory = useCallback(
(params?: CreateCategoriesParams) =>
ResourceService.createResourceCategory(params),
[]
)

const deleteCategory = useCallback(
(id?: string) => ResourceService.deleteResourceCategory(id ?? ''),
[]
Expand All @@ -118,12 +112,10 @@ const CategoriesContainer = () => {
onResponseError
})

const { response: allCategoriesNames, fetchData: fetchAllCategoriesNames } =
useAxios<CategoryNameInterface[]>({
service: ResourceService.getResourcesCategoriesNames,
defaultResponse: [],
onResponseError,
fetchOnMount: true
const { data: allCategoriesNames = [], refetch: fetchAllCategoriesNames } =
useQuery({
queryKey: ['categoriesNames'],
queryFn: ResourceService.getResourcesCategoriesName
})

const onCategoryUpdate = useCallback(async () => {
Expand All @@ -138,14 +130,11 @@ const CategoriesContainer = () => {
[fetchData, fetchAllCategoriesNames, onResponse]
)

const { fetchData: handleCreateCategory } = useAxios({
service: createCategory,
defaultResponse: null,
fetchOnMount: false,
onResponseError,
onResponse: onCategoryCreate
const { mutate: handleCreateCategory } = useMutation({
mutationFn: ResourceService.createResourceCategory,
onSuccess: onCategoryCreate,
onError: onResponseError
})

const existingCategoriesNames = allCategoriesNames?.map((item) => item.name)

const onAdd = () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ const ResourcesToolBarDrawer: FC<ResourcesToolBarDrawerProps> = ({
handleNonInputValueChange('sortBy', value)

const onApplyFilters = () => {
setCategories(data.categories)
setCategories(data.categories ?? [])
setSearch(data.name)
onRequestSort(data.sortBy)
closeDrawer()
Expand All @@ -84,8 +84,8 @@ const ResourcesToolBarDrawer: FC<ResourcesToolBarDrawerProps> = ({
<FiltersToggle handleToggle={onToggle} />
<AppButtonMenu<CategoryNameInterface>
customSx={styles.filter}
selectedItems={data.categories}
service={ResourceService.getResourcesCategoriesNames}
selectedItems={data.categories ?? []}
service={ResourceService.getResourcesCategoriesName}
setSelectedItems={onCategoryChange}
showNoneProperty
slotProps={{ paper: styles.filterPaper(isMobile) }}
Expand Down
17 changes: 14 additions & 3 deletions src/services/resource-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,10 +158,21 @@ export const ResourceService = {
getResourcesCategoriesNames: (): Promise<
AxiosResponse<CategoryNameInterface[]>
> => axiosClient.get(URLs.resources.resourcesCategories.getNames),
getResourcesCategoriesName: () => {
return baseService.request<CategoryNameInterface[]>({
method: 'GET',
url: URLs.resources.resourcesCategories.getNames
})
},
createResourceCategory: async (
params?: CreateCategoriesParams
): Promise<AxiosResponse<Categories>> =>
await axiosClient.post(URLs.resources.resourcesCategories.post, params),
params: CreateCategoriesParams
): Promise<Categories> => {
amoutens marked this conversation as resolved.
Show resolved Hide resolved
return await baseService.request<Categories>({
ShadowOfTheSpace marked this conversation as resolved.
Show resolved Hide resolved
method: 'POST',
url: URLs.resources.resourcesCategories.post,
data: params
})
},
deleteResourceCategory: async (id: string): Promise<AxiosResponse> =>
await axiosClient.delete(
createUrlPath(URLs.resources.resourcesCategories.delete, id)
Expand Down
9 changes: 6 additions & 3 deletions src/types/services/types/services.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,12 @@ export type ServiceFunction<Response, Params = undefined> = (
params: Params extends undefined ? undefined : Params
) => Promise<AxiosResponse<Response>>

export type ServiceFunctionNew<Response, Params = undefined> = (
params: Params extends undefined ? undefined : Params
) => Promise<Response>
export type ServiceFunctionNew<
Response,
Params = undefined
> = Params extends undefined
? () => Promise<Response>
: (params: Params) => Promise<Response>

export interface AxiosResponseError extends AxiosError<ErrorResponse> {
config: InternalAxiosRequestConfig & { _isRetry: boolean }
Expand Down
16 changes: 3 additions & 13 deletions tests/unit/components/app-button-menu/AppButtonMenu.spec.jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { render, screen, fireEvent } from '@testing-library/react'
import { screen, fireEvent } from '@testing-library/react'
import AppButtonMenu from '~/components/app-button-menu/AppButtonMenu'
import { renderWithProviders } from '~tests/test-utils'

vi.mock('simplebar-react', () => {
return {
Expand All @@ -20,11 +21,10 @@ vi.mock('react-i18next', () => ({
}
})
}))

beforeEach(() => {
const selectedItems = []

render(<AppButtonMenu selectedItems={selectedItems} />)
renderWithProviders(<AppButtonMenu selectedItems={selectedItems} />)
})

describe('AppButtonMenu', () => {
Expand All @@ -33,16 +33,6 @@ describe('AppButtonMenu', () => {

expect(buttonEl).toBeInTheDocument()
})

it('renders no items message after clicking if there are no selected items', () => {
const buttonEl = screen.getByRole('button')

fireEvent.click(buttonEl)

const el = screen.getByText('No items found')

expect(el).toBeInTheDocument()
})
it('input field should be in the component after clicking on a button', () => {
ShadowOfTheSpace marked this conversation as resolved.
Show resolved Hide resolved
const buttonEl = screen.getByRole('button')

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,4 +66,4 @@ describe('CategoryDropdown test', () => {
expect(newCategory).toBeInTheDocument()
})
})
})
})
ShadowOfTheSpace marked this conversation as resolved.
Show resolved Hide resolved
Loading
Loading