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

fix: API hooks #107

Merged
merged 15 commits into from
Jun 11, 2024
Merged
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
9 changes: 6 additions & 3 deletions src/components/BuySellForm/BuySellForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -215,11 +215,14 @@ const BuySellForm = ({ advertId, isModalOpen, onRequestClose }: TBuySellFormProp
}, [isSuccess, orderCreatedInfo, history, onRequestClose]);

useEffect(() => {
if (isError && error?.error.message) {
setErrorMessage(error?.error.message);
// @ts-expect-error types are not correct from api-hooks
if (isError && error?.message) {
// @ts-expect-error types are not correct from api-hooks
setErrorMessage(error?.message);
scrollRef.current?.scrollIntoView({ behavior: 'smooth', block: 'end' });
}
}, [error?.error.message, isError]);
// @ts-expect-error types are not correct from api-hooks
}, [error?.message, isError]);

return (
<form onSubmit={handleSubmit(onSubmit)}>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,28 +1,24 @@
import { useCallback, useState } from 'react';
import { useHistory } from 'react-router-dom';
import { TCurrency } from 'types';
import { MY_ADS_URL } from '@/constants';
import { api } from '@/hooks';
import useInvalidateQuery from '@/hooks/api/useInvalidateQuery';
import { Localize } from '@deriv-com/translations';
import { Button, Checkbox, Modal, Text, useDevice } from '@deriv-com/ui';
import './AdCreateEditSuccessModal.scss';

type TAdCreateEditSuccessModalProps = {
export type TAdCreateEditSuccessModalProps = {
advertsArchivePeriod?: number;
currency: TCurrency;
data: ReturnType<typeof api.advert.useCreate>['data'] | ReturnType<typeof api.advert.useUpdate>['data'];
isModalOpen: boolean;
limit: string;
onRequestClose: () => void;
visibilityStatus: string;
};

const AdCreateEditSuccessModal = ({
advertsArchivePeriod,
currency,
data,
isModalOpen,
limit,
onRequestClose,
visibilityStatus,
}: TAdCreateEditSuccessModalProps) => {
const { isMobile } = useDevice();
const invalidate = useInvalidateQuery();
Expand All @@ -35,12 +31,12 @@ const AdCreateEditSuccessModal = ({

const onClickOk = () => {
localStorage.setItem('should_not_show_auto_archive_message_again', JSON.stringify(isChecked));
if (visibilityStatus) {
if (data?.visibility_status && data?.account_currency && data.max_order_amount_limit_display) {
history.push(MY_ADS_URL, {
currency,
currency: data.account_currency,
from: '',
limit,
visibilityStatus,
limit: data.max_order_amount_limit_display,
visibilityStatus: data.visibility_status[0],
});
} else {
history.push(MY_ADS_URL);
Expand All @@ -49,12 +45,7 @@ const AdCreateEditSuccessModal = ({
onRequestClose();
};
return (
<Modal
ariaHideApp={false}
className='ad-create-edit-success-modal'
isOpen={isModalOpen}
onRequestClose={onRequestClose}
>
<Modal ariaHideApp={false} className='ad-create-edit-success-modal' isOpen={isModalOpen}>
<Modal.Header hideBorder hideCloseIcon>
<Text weight='bold'>
<Localize i18n_default_text='You’ve created an ad' />
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
import { TCurrency } from 'types';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import AdCreateEditSuccessModal from '../AdCreateEditSuccessModal';
import AdCreateEditSuccessModal, { TAdCreateEditSuccessModalProps } from '../AdCreateEditSuccessModal';

const mockProps = {
advertsArchivePeriod: 7,
currency: 'USD' as TCurrency,
data: {
account_currency: 'USD' as TCurrency,
max_order_amount_limit_display: '1000',
visibility_status: '',
},
isModalOpen: true,
limit: '1000',
onRequestClose: jest.fn(),
visibilityStatus: '',
};
} as unknown as TAdCreateEditSuccessModalProps;

jest.mock('@deriv-com/ui', () => ({
...jest.requireActual('@deriv-com/ui'),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ const BlockUnblockUserModal = ({
onClickBlocked?.();
onRequestClose();
} else if (error || unblockError) {
setErrorMessage?.(error?.error.message || unblockError?.error.message);
// @ts-expect-error types are not correct from api-hooks
setErrorMessage?.(error?.message || unblockError?.message);
onRequestClose();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ const EmailLinkVerifiedModal = ({ isModalOpen, onRequestClose, onSubmit }: TEmai
{{name}} in your bank account or e-wallet, hit the button below to
complete the order.'
values={{
amount: orderDetails.amount,
currency: orderDetails.local_currency,
amount: orderDetails?.amount,
currency: orderDetails?.local_currency,
name: orderDetails.advertiser_details.name,
}}
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ const InvalidVerificationLinkModal = ({
onRequestClose={onRequestClose}
>
<Modal.Body
className={clsx('flex flex-col items-center gap-[2.4rem] p-[2.4rem]', {
'py-0 px-[1.4rem] gap-[1.4rem]': isExcessiveErrorMobile,
className={clsx('flex flex-col items-center gap-[2.4rem] p-[2.4rem] lg:pb-[2.4rem] pb-0', {
'px-[1.4rem] gap-[1.4rem]': isExcessiveErrorMobile,
})}
>
<DerivLightIcEmailVerificationLinkInvalidIcon height={iconSize} width={iconSize} />
Expand Down
3 changes: 2 additions & 1 deletion src/components/Modals/NicknameModal/NicknameModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,8 @@ const NicknameModal = ({ isModalOpen, onRequestClose }: TNicknameModalProps) =>
data-testid='dt_nickname_modal_input'
error={!!error?.message || isError}
label={localize('Your nickname')}
message={createError?.error?.message || error?.message}
// @ts-expect-error types are not correct from api-hooks
message={createError?.message || error?.message}
onBlur={onBlur}
onChange={onChange}
value={value}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ const PaymentMethodFormModalRenderer = ({
<>
{!!isModalOpenFor('PaymentMethodErrorModal') && (
<PaymentMethodErrorModal
errorMessage={String(createError?.error?.message || updateError?.error?.message)}
errorMessage={String(createError?.message || updateError?.message)}
ameerul-deriv marked this conversation as resolved.
Show resolved Hide resolved
isModalOpen={!!isModalOpenFor('PaymentMethodErrorModal')}
onConfirm={() => {
onResetFormState();
Expand Down
7 changes: 3 additions & 4 deletions src/components/ProfileContent/ProfileContent.tsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,20 @@
import { Dispatch, SetStateAction, useEffect } from 'react';
import { TAdvertiserStats } from 'types';
import { AdvertiserName, AdvertiserNameToggle } from '@/components';
import { useAdvertiserStats } from '@/hooks/custom-hooks';
import { getCurrentRoute } from '@/utils';
import { useDevice } from '@deriv-com/ui';
import { ProfileBalance } from './ProfileBalance';
import { ProfileStats } from './ProfileStats';
import './ProfileContent.scss';

type TProfileContentProps = {
id?: string;
data: TAdvertiserStats;
ameerul-deriv marked this conversation as resolved.
Show resolved Hide resolved
setAdvertiserName?: (name: string) => void;
setShowOverlay?: Dispatch<SetStateAction<boolean>>;
};

const ProfileContent = ({ id, setAdvertiserName, setShowOverlay }: TProfileContentProps) => {
const ProfileContent = ({ data, setAdvertiserName, setShowOverlay }: TProfileContentProps) => {
const { isMobile } = useDevice();
const { data } = useAdvertiserStats(id);
const isMyProfile = getCurrentRoute() === 'my-profile';

useEffect(() => {
Expand Down
26 changes: 12 additions & 14 deletions src/components/ProfileContent/__tests__/ProfileContent.spec.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { TAdvertiserStats } from 'types';
import { useDevice } from '@deriv-com/ui';
import { render, screen } from '@testing-library/react';
import ProfileContent from '../ProfileContent';
Expand All @@ -21,19 +22,16 @@ jest.mock('@deriv-com/ui', () => ({
useDevice: jest.fn(() => ({ isMobile: false })),
}));

jest.mock('@/hooks/custom-hooks', () => ({
useAdvertiserStats: jest.fn(() => ({
data: {
isAddressVerified: false,
isIdentityVerified: false,
totalOrders: 10,
},
isLoading: false,
})),
}));

const mockUseDevice = useDevice as jest.Mock;

const mockProps = {
data: {
isAddressVerified: false,
isIdentityVerified: false,
totalOrders: 10,
} as TAdvertiserStats,
};

describe('ProfileContent', () => {
it('should render the advertiser name and profile balance if location is my-profile', () => {
Object.defineProperty(window, 'location', {
Expand All @@ -42,7 +40,7 @@ describe('ProfileContent', () => {
},
writable: true,
});
render(<ProfileContent />);
render(<ProfileContent {...mockProps} />);
expect(screen.getByText('AdvertiserName')).toBeInTheDocument();
expect(screen.getByText('ProfileBalance')).toBeInTheDocument();
});
Expand All @@ -54,7 +52,7 @@ describe('ProfileContent', () => {
},
writable: true,
});
render(<ProfileContent />);
render(<ProfileContent {...mockProps} />);
expect(screen.getByText('AdvertiserName')).toBeInTheDocument();
expect(screen.getByText('ProfileStats')).toBeInTheDocument();
});
Expand All @@ -70,7 +68,7 @@ describe('ProfileContent', () => {
mockUseDevice.mockReturnValue({
isMobile: true,
});
render(<ProfileContent />);
render(<ProfileContent {...mockProps} />);
expect(screen.getByText('AdvertiserNameToggle')).toBeInTheDocument();
});
});
4 changes: 1 addition & 3 deletions src/hooks/__tests__/useIsAdvertiser.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,7 @@ describe('useIsAdvertiser', () => {
...mockUseGetInfo,
data: {},
error: {
error: {
code: 'AdvertiserNotFound',
},
code: 'AdvertiserNotFound',
},
});

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useEffect } from 'react';
import { DeepPartial } from 'react-hook-form';
import { useLocalStorage } from 'usehooks-ts';
import { useP2PAdvertiserInfo } from '@deriv-com/api-hooks';
import { useP2PAdvertiserInfo, useSubscribe } from '@deriv-com/api-hooks';

type TP2PAdvertiserInfo = ReturnType<typeof useP2PAdvertiserInfo>['data'] & {
has_basic_verification: boolean;
Expand All @@ -16,7 +16,7 @@ type TP2PAdvertiserInfo = ReturnType<typeof useP2PAdvertiserInfo>['data'] & {

/** This custom hook returns information about the given advertiser ID */
const useAdvertiserInfo = (id?: string) => {
const { data, error, subscribe, ...rest } = useP2PAdvertiserInfo() ?? {};
const { data, error, subscribe, ...rest } = useSubscribe('p2p_advertiser_info') ?? {};

/**
* Use different local storage key for each advertiser, one to keep the current user's info, the other to keep the advertiser's info
Expand All @@ -33,7 +33,7 @@ const useAdvertiserInfo = (id?: string) => {
// Add additional information to the p2p_advertiser_info data
useEffect(() => {
if (data) {
const advertiser_info = data;
const advertiser_info = data.p2p_advertiser_info;
ameerul-deriv marked this conversation as resolved.
Show resolved Hide resolved

if (!advertiser_info) return;

Expand Down
10 changes: 5 additions & 5 deletions src/hooks/api/order/p2p-order/useOrderInfo.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { useMemo } from 'react';
import { useP2POrderInfo } from '@deriv-com/api-hooks';
import { useSubscribe } from '@deriv-com/api-hooks';

// TODO: Convert this to use useSubscribe as it is a subscribable endpoint
/** This custom hook that returns information about the given order ID */
const useOrderInfo = () => {
const { data, ...rest } = useP2POrderInfo();
const { data, ...rest } = useSubscribe('p2p_order_info');

// modify the data to add additional information
const modified_data = useMemo(() => {
if (!data) return undefined;
if (!data?.p2p_order_info) return undefined;

const {
advert_details,
Expand All @@ -19,10 +19,10 @@ const useOrderInfo = () => {
is_seen,
review_details,
verification_pending,
} = data;
} = data.p2p_order_info;

return {
...data,
...data.p2p_order_info,
advert_details: {
...advert_details,
/** Indicates if this is block trade advert or not. */
Expand Down
6 changes: 3 additions & 3 deletions src/hooks/api/settings/p2p-settings/useSettings.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useEffect } from 'react';
import { DeepPartial } from 'react-hook-form';
import { useLocalStorage } from 'usehooks-ts';
import { useP2PSettings } from '@deriv-com/api-hooks';
import { useP2PSettings, useSubscribe } from '@deriv-com/api-hooks';

type TP2PSettings =
| (ReturnType<typeof useP2PSettings>['data'] & {
Expand Down Expand Up @@ -31,12 +31,12 @@ type TCurrencyListItem = {
};

const useSettings = () => {
const { data, ...rest } = useP2PSettings();
const { data, ...rest } = useSubscribe('p2p_settings');
const [p2pSettings, setP2PSettings] = useLocalStorage<DeepPartial<TP2PSettings>>('p2p_settings', {});

useEffect(() => {
if (data) {
const p2p_settings_data = data;
const p2p_settings_data = data.p2p_settings;

if (!p2p_settings_data) return undefined;

Expand Down
4 changes: 3 additions & 1 deletion src/hooks/custom-hooks/useAdvertiserStats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ const useAdvertiserStats = (advertiserId?: string) => {
if (advertiserId) {
subscribe({ id: advertiserId });
}
}, [advertiserId, subscribe]);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [advertiserId]);

useEffect(() => {
return () => {
Expand Down Expand Up @@ -130,6 +131,7 @@ const useAdvertiserStats = (advertiserId?: string) => {
isIdle,
isLoading,
isSubscribed,
unsubscribe,
};
};

Expand Down
19 changes: 12 additions & 7 deletions src/hooks/custom-hooks/useExtendedOrderDetails.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,12 +106,16 @@ const useExtendedOrderDetails = ({
};
},
get displayPaymentAmount() {
return removeTrailingZeros(
FormatUtils.formatMoney(
Number(this.amount_display) * Number(roundOffDecimal(this.rate, setDecimalPlaces(this.rate, 6))),
{ currency: this.local_currency as TCurrency }
)
);
if (this.rate) {
ameerul-deriv marked this conversation as resolved.
Show resolved Hide resolved
return removeTrailingZeros(
FormatUtils.formatMoney(
Number(this.amount_display) *
Number(roundOffDecimal(this.rate, setDecimalPlaces(this.rate, 6))),
{ currency: this.local_currency as TCurrency }
)
);
}
return '';
},
get hasReviewDetails() {
return !!this.review_details;
Expand Down Expand Up @@ -170,7 +174,7 @@ const useExtendedOrderDetails = ({
return this.isBuyerConfirmedOrder || this.isBuyerCancelledOrder;
},
get isOrderReviewable() {
return this.is_reviewable;
return !!this.is_reviewable;
},
get isPendingOrder() {
return this.status === ORDERS_STATUS.PENDING;
Expand Down Expand Up @@ -231,6 +235,7 @@ const useExtendedOrderDetails = ({
);
},
get rateAmount() {
if (!this.rate) return '';
return removeTrailingZeros(
FormatUtils.formatMoney(this.rate, {
currency: this.local_currency as TCurrency,
Expand Down
3 changes: 3 additions & 0 deletions src/hooks/custom-hooks/useIsAdvertiser.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-nocheck error types are not correct from api-hooks
// TODO: fix error types from api-hooks
import { useEffect, useState } from 'react';
import { ERROR_CODES } from '@/constants';
import { isEmptyObject } from '@/utils';
Expand Down
Loading
Loading