added logical calculations to currency card data

This commit is contained in:
noumantahir 2022-02-12 00:13:35 +05:00
parent d99033f482
commit 2ce8f2ac7c
3 changed files with 196 additions and 126 deletions

View File

@ -1,96 +1,102 @@
import { View, Text, Dimensions } from 'react-native'; import { View, Text, Dimensions } from 'react-native';
import React, { useEffect, useState } from 'react'; import React from 'react';
import styles from './styles'; import styles from './styles';
import { import {
LineChart, LineChart,
} from "react-native-chart-kit"; } from "react-native-chart-kit";
import EStyleSheet from 'react-native-extended-stylesheet'; import EStyleSheet from 'react-native-extended-stylesheet';
import { fetchMarketChart } from '../../../providers/coingecko/coingecko';
interface CurrencyCardProps { export interface CurrencyCardProps {
chartData:number[]
id:string, id:string,
notToken:boolean tokenName:string,
notCryptoToken:boolean,
tokenSymbol:string,
currencySymbol:string,
changePercent:number,
currentValue:number,
ownedTokens:number,
} }
const CurrencyCard = ({id, notToken}:CurrencyCardProps) => { const CurrencyCard = ({
id,
notCryptoToken,
chartData,
tokenName,
currencySymbol,
tokenSymbol,
changePercent,
currentValue,
ownedTokens,
}:CurrencyCardProps) => {
const [prices, setPrices] = useState<number[]>([]); console.log(chartData);
if(!notCryptoToken && !chartData.length){
return null
useEffect(()=>{
if(!notToken){
_fetchData();
} }
},[id])
const _fetchData = async () => {
try{
const _data = await fetchMarketChart(id, 'usd', 30)
const _prices = _data.prices.map(item=>item.yValue).reverse();
setPrices(_prices)
} catch(err){
console.warn("failed to fetch market data", err)
}
}
const baseWidth = Dimensions.get("window").width - 32;
const chartWidth = baseWidth + baseWidth/(prices.length -1)
const _renderHeader = ( const _renderHeader = (
<View style={styles.cardHeader}> <View style={styles.cardHeader}>
<View style={styles.logo} /> {/* <View style={styles.logo} /> */}
<View style={styles.cardTitleContainer}> <View style={styles.cardTitleContainer}>
<Text style={styles.textTitle} >{id.toUpperCase()}</Text> <Text style={styles.textTitle} >{id}</Text>
<Text style={styles.textSubtitle}>{'Ecency Points'}</Text> <Text style={styles.textSubtitle}>{tokenName}</Text>
</View> </View>
<Text style={styles.textCurValue}><Text style={{fontWeight:'500'}}>{'5.17 ETH'}</Text>{'/$10.64'}</Text> <Text
style={styles.textCurValue}>
<Text style={{fontWeight:'500'}}>{`${ownedTokens} ${tokenSymbol}`}</Text>
{`/${(ownedTokens * currentValue).toFixed(2)}${currencySymbol}`}
</Text>
</View> </View>
); );
const _renderGraph = ( const _renderGraph = () => {
const _baseWidth = Dimensions.get("window").width - 32;
const _chartWidth = _baseWidth + _baseWidth/(chartData.length -1)
return (
<View style={styles.chartContainer}> <View style={styles.chartContainer}>
<LineChart <LineChart
data={{ data={{
labels: [],
datasets: [ datasets: [
{ {
data:prices data:chartData
} }
], ],
}} }}
width={chartWidth} // from react-native width={_chartWidth} // from react-native
height={130} height={130}
withHorizontalLabels={true} withHorizontalLabels={true}
withVerticalLabels={false} withVerticalLabels={false}
withDots={false} withDots={false}
withInnerLines={false} withInnerLines={false}
fromZero
chartConfig={{ chartConfig={{
backgroundColor:EStyleSheet.value('$white'), backgroundColor:EStyleSheet.value('$white'),
backgroundGradientFrom: EStyleSheet.value('$white'), backgroundGradientFrom: EStyleSheet.value('$white'),
backgroundGradientTo: EStyleSheet.value('$white'), backgroundGradientTo: EStyleSheet.value('$white'),
fillShadowGradient: EStyleSheet.value('$chartBlue'), fillShadowGradient: EStyleSheet.value('$chartBlue'),
fillShadowGradientOpacity:0.8, fillShadowGradientOpacity:0.8,
color: (opacity = 1) => 'transparent', color: () => 'transparent',
}} }}
/> />
</View> </View>
)}
)
const _renderFooter = ( const _renderFooter = (
<View style={styles.cardFooter}> <View style={styles.cardFooter}>
<Text style={styles.textCurValue}>$12.3</Text> <Text style={styles.textCurValue}>{`${currencySymbol} ${currentValue.toFixed(2)}`}</Text>
<Text style={styles.textDiffPositive}>+11%</Text> <Text style={ changePercent > 0 ? styles.textDiffPositive : styles.textDiffNegative}>{`${changePercent > 0 ? '+':''}${changePercent.toFixed(1)}%`}</Text>
</View> </View>
) )
return ( return (
<View style={styles.cardContainer}> <View style={styles.cardContainer}>
{_renderHeader} {_renderHeader}
{!notToken && _renderGraph} {!notCryptoToken && _renderGraph()}
{!notToken && _renderFooter} {!notCryptoToken && _renderFooter}
</View> </View>
); );
}; };

View File

@ -1,4 +1,30 @@
const WALLET_TOKENS = ['ecency', 'hive', 'hive_dollar'] interface WalletTokenBase {
id:string,
coingeckoId:string,
tokenName:string,
tokenSymbol:string,
notCryptoToken:boolean,
}
const WALLET_TOKENS = [{
id:'Ecency',
coingeckoId:'ecency',
tokenName:'Ecency Points',
tokenSymbol:'Points',
notCryptoToken:true
},{
id:'Hive',
coingeckoId:'hive',
tokenName:'Hive Token',
tokenSymbol:'Hive',
notCryptoToken:false
},{
id:'HBD',
coingeckoId:'hive_dollar',
tokenName:'Hive Dollar',
tokenSymbol:'HBD',
notCryptoToken:false
}] as WalletTokenBase[]
export default WALLET_TOKENS export default WALLET_TOKENS

View File

@ -31,6 +31,7 @@ import { useAppSelector } from '../../../hooks';
import CurrencyCard from '../children/currencyCard'; import CurrencyCard from '../children/currencyCard';
import WalletTokens from '../children/walletTokens'; import WalletTokens from '../children/walletTokens';
import WALLET_TOKENS from '../children/walletTokens'; import WALLET_TOKENS from '../children/walletTokens';
import { fetchMarketChart } from '../../../providers/coingecko/coingecko';
const HEADER_EXPANDED_HEIGHT = 312; const HEADER_EXPANDED_HEIGHT = 312;
@ -38,6 +39,7 @@ const WalletScreen = () => {
const intl = useIntl(); const intl = useIntl();
const isDarkTheme = useAppSelector((state) => state.application.isDarkTheme); const isDarkTheme = useAppSelector((state) => state.application.isDarkTheme);
const currency = useAppSelector((state)=>state.application.currency)
const [selectedUserActivities, setSelectedUserActivities] = useState(null); const [selectedUserActivities, setSelectedUserActivities] = useState(null);
const [filteredActivites, setFilteredActivites] = useState([]); const [filteredActivites, setFilteredActivites] = useState([]);
@ -46,6 +48,12 @@ const WalletScreen = () => {
const [refreshing, setRefreshing] = useState(false); const [refreshing, setRefreshing] = useState(false);
const [isExpanded, setIsExpanded] = useState(true); const [isExpanded, setIsExpanded] = useState(true);
const [marketData, setMarketData] = useState([]);
useEffect(()=>{
_fetchTokensData();
},[])
useEffect(() => { useEffect(() => {
if (selectedUserActivities) { if (selectedUserActivities) {
const activities = selectedUserActivities const activities = selectedUserActivities
@ -63,71 +71,100 @@ const WalletScreen = () => {
} }
}, [selectedUserActivities]); }, [selectedUserActivities]);
const _handleSwipeItemChange = (userActivities, _isLoading) => { const _fetchTokensData = () => {
setSelectedUserActivities(userActivities); WALLET_TOKENS.forEach(async (token, index)=>{
setIsLoading(_isLoading);
setRefreshing(false);
};
const _renderHeaderComponent = () => { if(token.coingeckoId === 'ececny'){
return ( setMarketData([])
<>
<CollapsibleCard
expanded={true}
isExpanded={isExpanded}
noContainer
noBorder
locked
titleComponent={<View />}
handleOnExpanded={() => {
setIsExpanded(true);
}}
>
<View style={[styles.header, { height: HEADER_EXPANDED_HEIGHT }]}>
<Swiper
loop={false}
showsPagination={true}
index={0}
dotStyle={styles.dotStyle}
onIndexChanged={(index) => setCurrentIndex(index)}
>
<EstmView
index={0}
handleOnSelected={_handleSwipeItemChange}
refreshing={refreshing}
currentIndex={currentIndex}
/>
<HiveView
index={1}
handleOnSelected={_handleSwipeItemChange}
refreshing={refreshing}
currentIndex={currentIndex}
/>
<HbdView
index={2}
handleOnSelected={_handleSwipeItemChange}
refreshing={refreshing}
currentIndex={currentIndex}
/>
<HpView
index={3}
refreshing={refreshing}
handleOnSelected={_handleSwipeItemChange}
currentIndex={currentIndex}
/>
</Swiper>
</View>
</CollapsibleCard>
<SafeAreaView style={styles.header}> }
{currentIndex === 0 && <HorizontalIconList options={POINTS} optionsKeys={POINTS_KEYS} />}
</SafeAreaView> const marketChart = await fetchMarketChart(token.coingeckoId, currency.currency, 3, 'hourly');
</> marketData[index] = marketChart.prices.map(item=>item.yValue);
); setMarketData([...marketData]);
}; })
}
// const _handleSwipeItemChange = (userActivities, _isLoading) => {
// setSelectedUserActivities(userActivities);
// setIsLoading(_isLoading);
// setRefreshing(false);
// };
// const _renderHeaderComponent = () => {
// return (
// <>
// <CollapsibleCard
// expanded={true}
// isExpanded={isExpanded}
// noContainer
// noBorder
// locked
// titleComponent={<View />}
// handleOnExpanded={() => {
// setIsExpanded(true);
// }}
// >
// <View style={[styles.header, { height: HEADER_EXPANDED_HEIGHT }]}>
// <Swiper
// loop={false}
// showsPagination={true}
// index={0}
// dotStyle={styles.dotStyle}
// onIndexChanged={(index) => setCurrentIndex(index)}
// >
// <EstmView
// index={0}
// handleOnSelected={_handleSwipeItemChange}
// refreshing={refreshing}
// currentIndex={currentIndex}
// />
// <HiveView
// index={1}
// handleOnSelected={_handleSwipeItemChange}
// refreshing={refreshing}
// currentIndex={currentIndex}
// />
// <HbdView
// index={2}
// handleOnSelected={_handleSwipeItemChange}
// refreshing={refreshing}
// currentIndex={currentIndex}
// />
// <HpView
// index={3}
// refreshing={refreshing}
// handleOnSelected={_handleSwipeItemChange}
// currentIndex={currentIndex}
// />
// </Swiper>
// </View>
// </CollapsibleCard>
// <SafeAreaView style={styles.header}>
// {currentIndex === 0 && <HorizontalIconList options={POINTS} optionsKeys={POINTS_KEYS} />}
// </SafeAreaView>
// </>
// );
// };
const _renderItem = ({ item, index }) => { const _renderItem = ({ item, index }) => {
return <CurrencyCard id={item} notToken={item === 'ecency'} />; const _tokenMarketData = marketData[index] || [];
const _currentValue = item.id == 'Ecency' ? 1/150 : (_tokenMarketData[0] || 0);
const _changePercent =
_tokenMarketData.length > 0 ?
((_tokenMarketData[_tokenMarketData.length - 1] - _tokenMarketData[0])/(_tokenMarketData[_tokenMarketData.length - 1]))*100
:
0;
return (
<CurrencyCard
chartData={_tokenMarketData || []}
currentValue={_currentValue}
changePercent={_changePercent}
currencySymbol={currency.currencySymbol}
ownedTokens={150}
{...item} />
);
}; };
const _renderLoading = () => { const _renderLoading = () => {
@ -168,6 +205,7 @@ const WalletScreen = () => {
<View style={styles.listWrapper}> <View style={styles.listWrapper}>
<FlatList <FlatList
data={WALLET_TOKENS} data={WALLET_TOKENS}
extraData={marketData}
style={globalStyles.tabBarBottom} style={globalStyles.tabBarBottom}
ListEmptyComponent={_renderLoading} ListEmptyComponent={_renderLoading}
renderItem={_renderItem} renderItem={_renderItem}