vega-frontend-monorepo/apps/trading/components/last-24h-price-change/last-24h-price-change.tsx
botond 2211abbd72
chore: cleanup type gen (#2362)
* chore: remove apollo type gen and clean up types lib

* fix: format

* fix: tests

* fix: format

* fix: hammer token types til sh*t turns green

* fix: format

* fix: apparently format again

* fix: lint

* fix: build-specs

* fix: format

* chore: regen types

* chore: regenerate types again

* fix: format
2022-12-08 21:13:30 +00:00

95 lines
2.4 KiB
TypeScript

import { useCallback, useMemo, useRef, useState } from 'react';
import throttle from 'lodash/throttle';
import {
isNumeric,
t,
useDataProvider,
useYesterday,
} from '@vegaprotocol/react-helpers';
import { PriceCellChange } from '@vegaprotocol/ui-toolkit';
import * as Schema from '@vegaprotocol/types';
import type { CandleClose } from '@vegaprotocol/types';
import type { Candle } from '@vegaprotocol/market-list';
import { marketCandlesProvider } from '@vegaprotocol/market-list';
import { HeaderStat } from '../header';
import * as constants from '../constants';
interface Props {
marketId?: string;
decimalPlaces?: number;
initialValue?: string[];
isHeader?: boolean;
noUpdate?: boolean;
}
export const Last24hPriceChange = ({
marketId,
decimalPlaces,
initialValue,
isHeader = false,
noUpdate = false,
}: Props) => {
const [candlesClose, setCandlesClose] = useState<string[]>(
initialValue || []
);
const yesterday = useYesterday();
// Cache timestamp for yesterday to prevent full unmount of market page when
// a rerender occurs
const yTimestamp = useMemo(() => {
return new Date(yesterday).toISOString();
}, [yesterday]);
const variables = useMemo(
() => ({
marketId: marketId,
interval: Schema.Interval.INTERVAL_I1H,
since: yTimestamp,
}),
[marketId, yTimestamp]
);
const throttledSetCandles = useRef(
throttle((data: Candle[]) => {
if (!noUpdate) {
const candlesClose: string[] = data
.map((candle) => candle?.close)
.filter((c): c is CandleClose => c !== null);
setCandlesClose(candlesClose);
}
}, constants.DEBOUNCE_UPDATE_TIME)
).current;
const update = useCallback(
({ data }: { data: Candle[] | null }) => {
if (data) {
throttledSetCandles(data);
}
return true;
},
[throttledSetCandles]
);
const { error } = useDataProvider<Candle[], Candle>({
dataProvider: marketCandlesProvider,
update,
variables,
skip: noUpdate || !marketId,
});
const content = useMemo(() => {
if (error || !isNumeric(decimalPlaces)) {
return <>-</>;
}
return (
<PriceCellChange candles={candlesClose} decimalPlaces={decimalPlaces} />
);
}, [candlesClose, decimalPlaces, error]);
return isHeader ? (
<HeaderStat heading={t('Change (24h)')} testId="market-change">
{content}
</HeaderStat>
) : (
content
);
};