Skip to content

Instantly share code, notes, and snippets.

@danielsmykowski1
Created November 23, 2019 23:45
Show Gist options
  • Select an option

  • Save danielsmykowski1/0a22140f8f77662e3210616b5efa3606 to your computer and use it in GitHub Desktop.

Select an option

Save danielsmykowski1/0a22140f8f77662e3210616b5efa3606 to your computer and use it in GitHub Desktop.
MainScreen Component of a React-Native project
import React, { Component, Fragment } from 'react';
import {
SafeAreaView, View, ActivityIndicator, StyleSheet, Platform
} from 'react-native';
import { Text } from 'react-native-elements';
import Carousel from 'react-native-snap-carousel';
import moment from 'moment';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { Auth } from 'aws-amplify';
import firebase from 'react-native-firebase';
import { GradientElementHeader } from '../../components/Navigation/GradientHeader';
import CountDown from '../../components/Modules/CountDown';
import GradientButton from '../../components/Buttons/GradientButton';
import CircleIconButton from '../../components/Buttons/CircleIconButton';
import MainSlide from './MainSlide';
import FormatHelper from '../../helpers/FormatHelper';
import Api from '../../apis/app';
import { setUser, setWallet, setGames } from '../../actions/common';
import {
Colors, Styles, Metrics, Fonts
} from '../../themes';
const styles = {
carousel: {
position: 'absolute',
width: '100%',
height: '100%',
left: 0,
top: 0
},
controls: {
position: 'absolute',
width: '100%',
bottom: 0,
left: 0
},
money: {
color: Colors.warning,
fontFamily: Fonts.family.primary.black,
fontSize: 50,
marginBottom: 10,
textShadowOffset: { width: 3, height: 3 },
textShadowRadius: 6,
textShadowColor: Colors.black,
textAlign: 'center'
},
navigation: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center'
},
navigationLeft: {
marginRight: 10
},
navigationRight: {
marginLeft: 10
},
endingIn: {
fontFamily: Fonts.family.primary.bold,
fontSize: Fonts.size.sm,
marginBottom: 10,
textAlign: 'center'
},
action: {
marginVertical: 20,
flexDirection: 'row'
},
actionItem: {
flex: 1,
marginHorizontal: 20
}
};
class MainScreen extends Component {
constructor(props) {
super(props);
this.state = {
activeSlide: 0,
loading: true
};
this.carouselRef = React.createRef();
}
async componentWillMount() {
// GetWallet Information
let user = null;
try {
user = await Auth.currentAuthenticatedUser();
this.props.setUser(user);
} catch (e) {
// Exception
}
if (user === null) {
this.props.navigation.navigate('authStack');
return;
}
if (!this.props.wallet) {
const {
response, body
} = await Api.get('maethergames/wallet/getWallet', {
UserId: user.username
});
if (response.status === 200 && !body.Error) {
if (body.Data.length === 0) {
await Api.post('maethergames/wallet/addWallet', {
UserId: user.username
});
const {
response: response1, body: body1
} = await Api.get('maethergames/wallet/getWallet', {
UserId: user.username
});
if (response1.status === 200 && !body1.Error && body1.Data.length > 0) {
await this.props.setWallet(body1.Data[0]);
}
} else {
await this.props.setWallet(body.Data[0]);
}
}
}
// Get Game
if (!this.props.games || this.props.games.length === 0) {
const {
response, body
} = await Api.get('maethergames/game/getGame');
switch (response.status) {
case 200:
await this.props.setGames(body.Data);
break;
default:
break;
}
}
const fcmToken = await firebase.messaging().getToken();
await Api.post('maethergames/device/setUserDevice', {
UserId: user.username,
Token: fcmToken,
Type: Platform.OS === 'android' ? 'A' : 'I'
});
this.onTokenRefreshListener = firebase.messaging().onTokenRefresh((fcmToken) => {
Api.post('maethergames/device/setUserDevice', {
UserId: user.username,
Token: fcmToken,
Type: Platform.OS === 'android' ? 'A' : 'I'
});
});
await this.setState({
loading: false
});
}
componentWillUnmount() {
this.onTokenRefreshListener();
}
handlePrev = () => {
const {
activeSlide
} = this.state;
if (activeSlide > 0) {
this.carouselRef.current.snapToPrev();
}
}
handleNext = () => {
const {
activeSlide
} = this.state;
const {
games
} = this.props;
if (activeSlide < games.length - 1) {
this.carouselRef.current.snapToNext();
}
}
handlePlay = () => {
const {
activeSlide
} = this.state;
const {
games
} = this.props;
this.props.navigation.navigate('gamePlay', { data: games[activeSlide] });
}
handleResult = () => {
this.props.navigation.navigate('gameResult');
}
renderItem = ({ item }) => (<MainSlide data={item} />)
render() {
const {
activeSlide, loading
} = this.state;
const {
games
} = this.props;
const game = games && games.length > 0 ? games[activeSlide] : null;
let seconds = 0;
if (game) {
const drawAt = moment(game.DrawAt);
const now = moment(new Date());
seconds = drawAt.diff(now, 'seconds');
}
return (
<View style={Styles.mainContainer}>
<GradientElementHeader
containerStyle={Styles.elementHeader}
backgroundColor={Colors.transparent}
centerComponent={{
text: 'GAME',
style: Styles.headerTitle
}}
/>
<View style={Styles.container}>
{
loading ? (
<View style={StyleSheet.flatten([Styles.core, Styles.container])}>
<ActivityIndicator color={Colors.white} />
</View>
) : (
games && games.length > 0 ? (
<Fragment>
<View style={styles.carousel}>
<Carousel
ref={this.carouselRef}
data={games}
renderItem={this.renderItem}
sliderWidth={Metrics.dimension.width}
itemWidth={Metrics.dimension.width}
onSnapToItem={(activeSlide) => { this.setState({ activeSlide }); }}
inactiveSlideScale={1}
inactiveSlideOpacity={1}
/>
</View>
<View style={styles.controls}>
<Text style={styles.money}>
{`$ ${FormatHelper.formatScale(parseInt(game.Price, 2), 2)}`}
</Text>
<View style={styles.navigation}>
<CircleIconButton
style={styles.navigationLeft}
icon="chevron-left"
size="lg"
onPress={this.handlePrev}
/>
<View>
<Text style={styles.endingIn}>Ending In</Text>
<CountDown
until={seconds}
size={18}
onFinish={() => { }}
digitStyle={Styles.countDownDigital}
digitTxtStyle={Styles.countDownDigitText}
timeLabelStyle={Styles.countDownTimeLabel}
timeToShow={['D', 'H', 'M', 'S']}
timeLabels={{
d: 'Days', h: 'Hours', m: 'Mins', s: 'Secs'
}}
/>
</View>
<CircleIconButton
style={styles.navigationRight}
icon="chevron-right"
size="lg"
onPress={this.handleNext}
/>
</View>
<SafeAreaView style={styles.action}>
<View style={styles.actionItem}>
<GradientButton
onPress={this.handleResult}
title="RESULT"
color="info"
/>
</View>
<View style={styles.actionItem}>
<GradientButton
onPress={this.handlePlay}
title="PLAY!"
/>
</View>
</SafeAreaView>
</View>
</Fragment>
) : null
)
}
</View>
</View>
);
}
}
const mapStateToProps = state => ({
wallet: state.common.wallet,
games: state.common.games
});
const mapDispatchToProps = dispatch => ({
dispatch,
setUser: bindActionCreators(setUser, dispatch),
setWallet: bindActionCreators(setWallet, dispatch),
setGames: bindActionCreators(setGames, dispatch)
});
export default connect(mapStateToProps, mapDispatchToProps)(MainScreen);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment