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 13 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
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
2 changes: 1 addition & 1 deletion src/hooks/custom-hooks/useSendbird.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ function createChatMessage(sendbirdMessage: BaseMessage): ChatMessage {
};
}

const useSendbird = (orderId: string, isErrorOrderInfo: boolean, chatChannelUrl: string) => {
const useSendbird = (orderId: string | undefined, isErrorOrderInfo: boolean, chatChannelUrl: string) => {
const sendbirdApiRef = useRef<ReturnType<typeof SendbirdChat.init<GroupChannelModule[]>>>();

const [isChatLoading, setIsChatLoading] = useState(false);
Expand Down
13 changes: 8 additions & 5 deletions src/pages/advertiser/screens/Advertiser/Advertiser.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { useHistory, useLocation, useParams } from 'react-router-dom';
import { PageReturn, ProfileContent } from '@/components';
import BlockDropdown from '@/components/AdvertiserName/BlockDropdown';
import { BUY_SELL_URL, MY_PROFILE_URL } from '@/constants';
import { api, useModalManager } from '@/hooks';
import { api, useAdvertiserStats, useModalManager } from '@/hooks';
import { useTranslations } from '@deriv-com/translations';
import { useDevice } from '@deriv-com/ui';
import { AdvertiserAdvertsTable } from '../AdvertiserAdvertsTable';
Expand All @@ -25,18 +25,21 @@ const Advertiser = () => {
const history = useHistory();
const location = useLocation();

const { data, unsubscribe } = useAdvertiserStats(id);

return (
<div className='advertiser'>
<PageReturn
className='lg:mt-0'
hasBorder={isMobile}
onClick={() =>
onClick={() => {
history.push(
(location.state as { from: string })?.from === 'MyProfile'
? `${MY_PROFILE_URL}?tab=My+counterparties`
: BUY_SELL_URL
)
}
);
unsubscribe();
}}
pageTitle={localize('Advertiser’s page')}
{...(isMobile && {
rightPlaceHolder: (
Expand All @@ -58,7 +61,7 @@ const Advertiser = () => {
onClickUnblock={() => showModal('BlockUnblockUserModal')}
setShowOverlay={setShowOverlay}
>
<ProfileContent id={id} setAdvertiserName={setAdvertiserName} setShowOverlay={setShowOverlay} />
<ProfileContent data={data} setAdvertiserName={setAdvertiserName} setShowOverlay={setShowOverlay} />
ameerul-deriv marked this conversation as resolved.
Show resolved Hide resolved
<AdvertiserAdvertsTable advertiserId={advertiserId} />
</AdvertiserBlockOverlay>
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,13 @@ jest.mock('@/hooks', () => ({
})),
}));

jest.mock('@/hooks/custom-hooks', () => ({
useAdvertiserStats: jest.fn(() => ({
data: {},
unsubscribe: jest.fn(),
})),
}));

jest.mock('@deriv-com/ui', () => ({
...jest.requireActual('@deriv-com/ui'),
useDevice: jest.fn(() => ({ isMobile: false })),
Expand Down
6 changes: 4 additions & 2 deletions src/pages/my-ads/screens/CreateEditAd/CreateEditAd.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -230,8 +230,10 @@ const CreateEditAd = () => {
</form>
</FormProvider>
<AdCreateEditErrorModal
errorCode={(error?.error?.code || updateError?.error?.code) as TErrorCodes}
errorMessage={(error?.error?.message || updateError?.error?.message) ?? 'Something’s not right'}
// @ts-expect-error types are not correct from api-hooks
errorCode={(error?.code || updateError?.code) as TErrorCodes}
// @ts-expect-error types are not correct from api-hooks
errorMessage={(error?.message || updateError?.message) ?? 'Something’s not right'}
isModalOpen={!!isModalOpenFor('AdCreateEditErrorModal')}
onRequestClose={hideModal}
/>
Expand Down
2 changes: 1 addition & 1 deletion src/pages/my-ads/screens/MyAds/MyAds.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ const MyAds = () => {
if (!isPoaVerified || !isPoiVerified) return <Verification />;

return (
<div className={clsx('flex flex-col', isMobile ? 'h-[calc(100vh-12rem)]' : 'h-full')}>
<div className={clsx('flex flex-col', isMobile ? 'h-[calc(100vh-8rem)]' : 'h-full')}>
{isAdvertiserBarred && <TemporarilyBarredHint />}
<MyAdsTable />
</div>
Expand Down
Loading
Loading