pointsContainer convert to hooks

This commit is contained in:
ue 2019-11-17 16:12:32 +03:00
parent bfd2d9f60d
commit 0dd2d9d8df
4 changed files with 94 additions and 117 deletions

View File

@ -20,7 +20,7 @@ const BoostPlaceHolder = () => {
{({ isDarkTheme }) => { {({ isDarkTheme }) => {
const color = isDarkTheme ? '#2e3d51' : '#f5f5f5'; const color = isDarkTheme ? '#2e3d51' : '#f5f5f5';
return ( return (
<View style={styles.container} key={i}> <View style={styles.container} key={i.toString()}>
<View style={styles.line}> <View style={styles.line}>
<Placeholder.Box color={color} width={90} height={40} animate="fade" /> <Placeholder.Box color={color} width={90} height={40} animate="fade" />
<View style={styles.paragraphWrapper}> <View style={styles.paragraphWrapper}>

View File

@ -123,7 +123,7 @@ const PointsView = ({
<View style={styles.listWrapper}> <View style={styles.listWrapper}>
<FlatList <FlatList
data={userActivities} data={userActivities}
keyExtractor={item => item.id.toString()} keyExtractor={item => get(item, 'created').toString()}
ListEmptyComponent={_renderLoading()} ListEmptyComponent={_renderLoading()}
renderItem={({ item, index }) => ( renderItem={({ item, index }) => (
<CollapsibleCard <CollapsibleCard

View File

@ -1,7 +1,6 @@
import React from 'react'; import React from 'react';
import { View, Text } from 'react-native'; import { View, Text } from 'react-native';
import get from 'lodash/get'; import get from 'lodash/get';
import { useIntl } from 'react-intl';
// Components // Components
import { MainButton, Icon } from '..'; import { MainButton, Icon } from '..';
@ -12,10 +11,8 @@ import styles from './productItemLineStyles';
const DEALS = { '9999points': 'BEST DEAL!', '4999points': 'POPULAR!' }; const DEALS = { '9999points': 'BEST DEAL!', '4999points': 'POPULAR!' };
const ProductItemLineView = ({ disabled, handleOnButtonPress, product, title }) => { const ProductItemLineView = ({ disabled, handleOnButtonPress, product, title }) => {
const intl = useIntl();
return ( return (
<View style={styles.boostLine} key={get(product, 'productId')}> <View style={styles.boostLine} key={get(product, 'productId').toString()}>
{_renderDeal(product)} {_renderDeal(product)}
<View style={styles.buttonWrapper}> <View style={styles.buttonWrapper}>
<MainButton <MainButton

View File

@ -1,8 +1,8 @@
import { Component } from 'react'; import React, { useState, useEffect, useCallback } from 'react';
import { Alert } from 'react-native'; import { Alert } from 'react-native';
import { connect } from 'react-redux'; import { connect, useDispatch } from 'react-redux';
import get from 'lodash/get'; import get from 'lodash/get';
import { injectIntl } from 'react-intl'; import { useIntl } from 'react-intl';
import { withNavigation } from 'react-navigation'; import { withNavigation } from 'react-navigation';
// Services and Actions // Services and Actions
@ -24,57 +24,58 @@ import ROUTES from '../constants/routeNames';
* *
*/ */
class PointsContainer extends Component { const PointsContainer = ({
constructor(props) { username,
super(props); isConnected,
this.state = { navigation,
userPoints: {}, children,
userActivities: null, accounts,
refreshing: false, currentAccount,
isClaiming: false, user,
isLoading: true, activeBottomTab,
navigationParams: {}, isPinCodeOpen,
}; globalProps,
} pinCode,
}) => {
// Component Life Cycle Functions const [userPoints, setUserPoints] = useState({});
componentDidMount() { const [userActivities, setUserActivities] = useState(null);
const { username, isConnected, navigation } = this.props; const [refreshing, setRefreshing] = useState(false);
const [isClaiming, setIsClaiming] = useState(false);
const [isLoading, setIsLoading] = useState(true);
const [navigationParams, setNavigationParams] = useState({});
const [balance, setBalance] = useState(0);
const intl = useIntl();
const dispatch = useDispatch();
const fetchInterval = useCallback(() => setInterval(_fetchUserPointActivities, 6 * 60 * 1000), [
_fetchUserPointActivities,
]);
useEffect(() => {
if (isConnected) { if (isConnected) {
this._fetchUserPointActivities(username); _fetchUserPointActivities(username);
this.fetchInterval = setInterval(this._fetchUserPointActivities, 6 * 60 * 1000); fetchInterval();
} }
if (get(navigation, 'state.params', null)) { if (get(navigation, 'state.params', null)) {
const navigationParams = get(navigation, 'state.params'); const _navigationParams = get(navigation, 'state.params');
this.setState({ navigationParams }); setNavigationParams(_navigationParams);
} }
} }, [_fetchUserPointActivities, fetchInterval, isConnected, navigation, username]);
UNSAFE_componentWillReceiveProps(nextProps) { useEffect(() => {
const { username } = this.props; if (isConnected && activeBottomTab === ROUTES.TABBAR.POINTS && username) {
const _username = get(nextProps, 'username'); _fetchUserPointActivities(username);
if (
nextProps.isConnected &&
((nextProps.activeBottomTab === ROUTES.TABBAR.POINTS && _username) ||
(_username !== username && _username))
) {
this._fetchUserPointActivities(_username);
} }
} }, [isConnected, username, _fetchUserPointActivities, activeBottomTab]);
componentWillUnmount() { useEffect(() => {
clearInterval(this.fetchInterval); return clearInterval(fetchInterval);
} });
// Component Functions // Component Functions
_handleOnDropdownSelected = index => { const _handleOnDropdownSelected = index => {
const { dispatch, isPinCodeOpen, navigation } = this.props;
const { balance } = this.state;
let navigateTo; let navigateTo;
let navigateParams; let navigateParams;
@ -123,35 +124,34 @@ class PointsContainer extends Component {
} }
}; };
_groomUserActivities = userActivities => const _groomUserActivities = _userActivities =>
userActivities.map(item => ({ _userActivities.map(item => ({
...item, ...item,
icon: get(POINTS[get(item, 'type')], 'icon'), icon: get(POINTS[get(item, 'type')], 'icon'),
iconType: get(POINTS[get(item, 'type')], 'iconType'), iconType: get(POINTS[get(item, 'type')], 'iconType'),
textKey: get(POINTS[get(item, 'type')], 'textKey'), textKey: get(POINTS[get(item, 'type')], 'textKey'),
})); }));
_fetchUserPointActivities = async username => { const _fetchUserPointActivities = useCallback(async _username => {
if (!username) { if (!_username) {
return; return;
} }
this.setState({ refreshing: true }); setRefreshing(true);
await getUser(username) await getUser(_username)
.then(userPoints => { .then(userPoints => {
const balance = Math.round(get(userPoints, 'points') * 1000) / 1000; const _balance = Math.round(get(userPoints, 'points') * 1000) / 1000;
this.setState({ userPoints, balance }); setUserPoints(userPoints);
setBalance(_balance);
}) })
.catch(err => { .catch(err => {
Alert.alert(get(err, 'message', 'Error')); Alert.alert(get(err, 'message', 'Error'));
}); });
await getUserPoints(username) await getUserPoints(_username)
.then(userActivities => { .then(userActivities => {
if (Object.entries(userActivities).length !== 0) { if (Object.entries(userActivities).length !== 0) {
this.setState({ setUserActivities(_groomUserActivities(userActivities));
userActivities: this._groomUserActivities(userActivities),
});
} }
}) })
.catch(err => { .catch(err => {
@ -160,17 +160,15 @@ class PointsContainer extends Component {
} }
}); });
this.setState({ setRefreshing(false);
refreshing: false, setIsLoading(false);
isLoading: false, }, []);
});
};
_getUserBalance = async username => { const _getUserBalance = async _username => {
await getUser(username) await getUser(_username)
.then(userPoints => { .then(_userPoints => {
const balance = Math.round(get(userPoints, 'points') * 1000) / 1000; const _balance = Math.round(get(_userPoints, 'points') * 1000) / 1000;
return balance; return _balance;
}) })
.catch(err => { .catch(err => {
if (err) { if (err) {
@ -179,14 +177,12 @@ class PointsContainer extends Component {
}); });
}; };
_claimPoints = async () => { const _claimPoints = async () => {
const { username } = this.props; setIsClaiming(true);
this.setState({ isClaiming: true });
await claim(username) await claim(username)
.then(() => { .then(() => {
this._fetchUserPointActivities(username); _fetchUserPointActivities(username);
}) })
.catch(error => { .catch(error => {
if (error) { if (error) {
@ -199,74 +195,58 @@ class PointsContainer extends Component {
} }
}); });
this.setState({ isClaiming: false }); setIsClaiming(false);
}; };
_boost = async (point, permlink, author, user) => { const _boost = async (point, permlink, author, _user) => {
const { currentAccount, pinCode, dispatch, intl, navigation } = this.props; setIsLoading(true);
this.setState({ isLoading: true });
await boost(user || currentAccount, pinCode, point, permlink, author) await boost(_user || currentAccount, pinCode, point, permlink, author)
.then(() => { .then(() => {
this.setState({ isLoading: false }); setIsLoading(false);
navigation.goBack(); navigation.goBack();
dispatch(toastNotification(intl.formatMessage({ id: 'alert.successful' }))); dispatch(toastNotification(intl.formatMessage({ id: 'alert.successful' })));
}) })
.catch(error => { .catch(error => {
if (error) { if (error) {
this.setState({ isLoading: false }); setIsLoading(false);
dispatch(toastNotification(intl.formatMessage({ id: 'alert.fail' }))); dispatch(toastNotification(intl.formatMessage({ id: 'alert.fail' })));
} }
}); });
}; };
_getESTMPrice = points => { const _getESTMPrice = points => {
const { globalProps } = this.props;
const { base, quote } = globalProps; const { base, quote } = globalProps;
return points * 0.01 * (base / quote); return points * 0.01 * (base / quote);
}; };
render() { return (
const { children &&
children({
accounts,
balance, balance,
boost: _boost,
claim: _claimPoints,
currentAccount,
currentAccountName: currentAccount.name,
fetchUserActivity: _fetchUserPointActivities,
getAccount,
getESTMPrice: _getESTMPrice,
getUserBalance: _getUserBalance,
getUserDataWithUsername,
handleOnDropdownSelected: _handleOnDropdownSelected,
isClaiming, isClaiming,
isLoading, isLoading,
navigationParams, navigationParams,
refreshing, refreshing,
userActivities, userActivities,
userPoints, userPoints,
} = this.state; redeemType: get(navigationParams, 'redeemType'),
const { children, accounts, currentAccount, user } = this.props; user,
})
return ( );
children && };
children({
accounts,
balance,
boost: this._boost,
claim: this._claimPoints,
currentAccount,
currentAccountName: currentAccount.name,
fetchUserActivity: this._fetchUserPointActivities,
getAccount,
getESTMPrice: this._getESTMPrice,
getUserBalance: this._getUserBalance,
getUserDataWithUsername,
handleOnDropdownSelected: this._handleOnDropdownSelected,
handleOnPressTransfer: this._handleOnPressTransfer,
isClaiming,
isLoading,
navigationParams,
refreshing,
userActivities,
userPoints,
redeemType: get(navigationParams, 'redeemType'),
user,
})
);
}
}
const mapStateToProps = state => ({ const mapStateToProps = state => ({
user: state.account.currentAccount, user: state.account.currentAccount,
@ -280,4 +260,4 @@ const mapStateToProps = state => ({
globalProps: state.account.globalProps, globalProps: state.account.globalProps,
}); });
export default withNavigation(connect(mapStateToProps)(injectIntl(PointsContainer))); export default withNavigation(connect(mapStateToProps)(PointsContainer));