Commit c9bd1136 by OuiAtichat

update main page get data from firebase

parent e1f1d4b7
...@@ -15,6 +15,7 @@ import { fixTimerWarning } from './utils/fixTimerWarning'; ...@@ -15,6 +15,7 @@ import { fixTimerWarning } from './utils/fixTimerWarning';
// import { default as customMapping } from './custom-mapping.json'; // import { default as customMapping } from './custom-mapping.json';
console.disableYellowBox = true; console.disableYellowBox = true;
const Application = () => { const Application = () => {
useEffect(() => { useEffect(() => {
fixTimerWarning(); fixTimerWarning();
......
...@@ -197,7 +197,7 @@ const WithBottomTabStack = createBottomTabNavigator( ...@@ -197,7 +197,7 @@ const WithBottomTabStack = createBottomTabNavigator(
Setting: SettingStack, Setting: SettingStack,
}, },
{ {
initialRouteName: 'Timer', // default SmartMeter initialRouteName: 'SmartMeter', // default SmartMeter
tabBarComponent: props => <BottomNavigationTabs {...props} />, tabBarComponent: props => <BottomNavigationTabs {...props} />,
tabBarOptions: { tabBarOptions: {
keyboardHidesTabBar: true, keyboardHidesTabBar: true,
...@@ -238,7 +238,7 @@ const AppStack = createSwitchNavigator( ...@@ -238,7 +238,7 @@ const AppStack = createSwitchNavigator(
Main: MainStack, Main: MainStack,
}, },
{ {
initialRouteName: 'Main', //default AuthLoading initialRouteName: 'AuthLoading', //default AuthLoading
} }
); );
......
import React from 'react'; import React, { Component } from 'react';
import { Card, View, Row, Icon, Text } from 'native-base'; import { Card, View, Row, Icon, Text } from 'native-base';
import { Image, TouchableOpacity, StyleSheet } from 'react-native'; import { Image, TouchableOpacity, StyleSheet } from 'react-native';
import { color, theme } from '../constants/Styles'; import { color, theme } from '../constants/Styles';
...@@ -43,30 +43,42 @@ const styles = StyleSheet.create({ ...@@ -43,30 +43,42 @@ const styles = StyleSheet.create({
}, },
}); });
const MeterCard = props => { class MeterCard extends Component {
render() {
return ( return (
<TouchableOpacity onPress={props.onPressEachCard}> <TouchableOpacity onPress={this.props.onPressEachCard}>
<Card style={[theme.rowContainer, { borderRadius: 8, marginBottom: 10 }]}> <Card style={[theme.rowContainer, { borderRadius: 8, marginBottom: 10, height: 136 }]}>
<View <View
style={[ style={[
styles.meterOn, styles.meterOn,
{ backgroundColor: props.isOn ? 'rgba(65, 204, 0, 0.59)' : 'rgba(223, 0, 0, 0.59)' }, { backgroundColor: this.props.isOn ? 'rgba(65, 204, 0, 0.59)' : 'rgba(223, 0, 0, 0.59)' },
]} ]}
> >
<Text style={[theme.smDescription, theme.textWhite]}>{props.isOn ? 'ON' : 'OFF'}</Text> <Text style={[theme.smDescription, theme.textWhite]}>{this.props.isOn ? 'ON' : 'OFF'}</Text>
</View> </View>
<View style={[theme.centerContainer]}> <View style={[theme.centerContainer]}>
<Image source={{ uri: props.img }} style={styles.meterImgStyle} /> {this.props.img ? (
<Image source={{ uri: this.props.img }} style={styles.meterImgStyle} />
) : (
<View
style={[
styles.meterImgStyle,
{ flex: 1, justifyContent: 'center', alignContent: 'center' },
]}
>
<Text style={{ fontSize: 10 }}>No Img</Text>
</View>
)}
</View> </View>
<View style={[theme.containerWithPadding, { flex: 2 }]}> <View style={[theme.containerWithPadding, { flex: 2 }]}>
{props.isOnline ? <View style={[styles.online]} /> : null} {this.props.isOnline ? <View style={[styles.online]} /> : null}
<Row style={{ alignItems: 'center' }}> <Row style={{ alignItems: 'center' }}>
<Text style={[theme.smallTitle, { marginRight: 15 }]}>{props.deviceName}</Text> <Text style={[theme.smallTitle, { marginRight: 15 }]}>{this.props.name}</Text>
<Icon name="people" style={{ color: color.darkGrey }} /> <Icon name="people" style={{ color: color.darkGrey }} />
</Row> </Row>
<Text style={[theme.smDescription]} numberOfLines={2}> <Text style={[theme.smDescription]} numberOfLines={2}>
{props.description} {this.props.description}
</Text> </Text>
<Row style={{ marginTop: 10 }}> <Row style={{ marginTop: 10 }}>
<View style={[styles.meterIconCover]}> <View style={[styles.meterIconCover]}>
...@@ -80,5 +92,6 @@ const MeterCard = props => { ...@@ -80,5 +92,6 @@ const MeterCard = props => {
</Card> </Card>
</TouchableOpacity> </TouchableOpacity>
); );
}; }
}
export default MeterCard; export default MeterCard;
...@@ -35,27 +35,45 @@ export const getAllDeviceInfoAction = allDeviceInfo => ({ ...@@ -35,27 +35,45 @@ export const getAllDeviceInfoAction = allDeviceInfo => ({
export const getAllDeviceInfo = () => async (dispatch, getState) => { export const getAllDeviceInfo = () => async (dispatch, getState) => {
const { currentUserReducer } = getState(); const { currentUserReducer } = getState();
const currentUserId = currentUserReducer.uid; const currentUserId = currentUserReducer.uid;
try {
const allOwnerDeviceId = await fireStore const allOwnerDevice = await fireStore
.collection('owner') .collection('owner')
.doc(currentUserId) .doc(currentUserId)
.get(); .get();
const allSharingDeviceId = await fireStore const allSharingDevice = await fireStore
.collection('sharing') .collection('sharing')
.doc(currentUserId) .doc(currentUserId)
.get(); .get();
const allDeviceId = Object.keys({ ...allOwnerDeviceId.data(), ...allSharingDeviceId.data() }); const allOwnerDeviceId = Object.keys({ ...allOwnerDevice.data() });
const allSharingDeviceId = Object.keys({ ...allSharingDevice.data() });
let alldeviceInfo = []; let alldeviceInfo = [];
await allDeviceId.map((deviceId, index) => { await allOwnerDeviceId.map((deviceId, index) => {
fireStore fireStore
.collection('device') .collection('device')
.doc(deviceId) .doc(deviceId)
.get() .get()
.then(deviceInfo => alldeviceInfo.push(deviceInfo.data())); .then(deviceInfo =>
alldeviceInfo.push(Object.assign(deviceInfo.data(), { deviceId, isSharing: false }))
);
}); });
await allSharingDeviceId.map((deviceId, index) => {
fireStore
.collection('device')
.doc(deviceId)
.get()
.then(deviceInfo =>
alldeviceInfo.push(Object.assign(deviceInfo.data(), { deviceId, isSharing: true }))
);
});
const allDataInfo = await alldeviceInfo;
console.log(allDataInfo);
return dispatch(getAllDeviceInfoAction(alldeviceInfo)); return dispatch(getAllDeviceInfoAction(allDataInfo));
} catch (error) {
alert(error);
}
}; };
export const SET_CURRENT_SELECTED = 'SET_CURRENT_SELECTED';
export const setCurrentSelectedAction = selectedDeviceId => ({
type: GET_CURRENT_SELECTED,
selectedDeviceId,
});
export const setCurrentSelected = DeviceId => async dispatch => {
return dispatch(setCurrentSelectedAction(DeviceId));
};
import { SET_CURRENT_SELECTED } from '../actions/currentSelectedAction';
const initState = {
selectedDeviceId: '',
};
const currentSelectedDeviceReducer = (state = initState, action) => {
switch (action.type) {
case SET_CURRENT_SELECTED:
return { ...state, selectedDeviceId: action.selectedDeviceId };
default:
return state;
}
};
export default currentSelectedDeviceReducer;
...@@ -3,9 +3,11 @@ import { combineReducers } from 'redux'; ...@@ -3,9 +3,11 @@ import { combineReducers } from 'redux';
import { reducer as form } from 'redux-form'; import { reducer as form } from 'redux-form';
import allDataReducer from './allDataReducer'; import allDataReducer from './allDataReducer';
import currentUserReducer from './currentUserReducer'; import currentUserReducer from './currentUserReducer';
import currentSelectedDeviceReducer from './currentSelectedReducer';
export default combineReducers({ export default combineReducers({
// token: authReducer, // token: authReducer,
currentSelectedDeviceReducer,
currentUserReducer, currentUserReducer,
allDataReducer, allDataReducer,
form, form,
......
import React, { Component } from 'react'; import React, { Component } from 'react';
import { Text } from 'native-base'; import { Text } from 'native-base';
import { FlatList, View } from 'react-native'; import { FlatList, View } from 'react-native';
import { theme } from '../../../constants/Styles'; import { theme } from '../../../constants/Styles';
import MeterCard from '../../../components/MeterCard'; import MeterCard from '../../../components/MeterCard';
import { HeaderButtons, Item } from 'react-navigation-header-buttons'; import { HeaderButtons, Item } from 'react-navigation-header-buttons';
import IoniconsHeaderButton from '../../../components/IoniconsHeaderButton'; import IoniconsHeaderButton from '../../../components/IoniconsHeaderButton';
import { isIphoneX } from '../../../utils/isPhoneX'; import { isIphoneX } from '../../../utils/isPhoneX';
import { getAllDeviceInfo } from '../../../reduxStore/actions/allDataAction';
import { setCurrentSelected } from '../../../reduxStore/actions/currentSelectedAction';
import { connect } from 'react-redux';
const Meter = [ let Data = [
{ // {
deviceName: 'Device 1', // deviceName: 'Device 1',
description: 'Lorem ipsum dolorsit amet,consectetur adipiscing elit. Cras sagitti.', // description: 'Lorem ipsum dolorsit amet,consectetur adipiscing elit. Cras sagitti.',
img: 'https://www.tunnelbear.com/static/img/android@2x.b83f4df.png', // img: 'https://www.tunnelbear.com/static/img/android@2x.b83f4df.png',
isOnline: true, // isOnline: true,
isOn: true, // isOn: true,
}, // },
{ // {
deviceName: 'Device 2', // deviceName: 'Device 2',
description: 'Lorem ipsum dolorsit amet,consectetur adipiscing elit. Cras sagitti.', // description: 'Lorem ipsum dolorsit amet,consectetur adipiscing elit. Cras sagitti.',
img: 'https://www.tunnelbear.com/static/img/android@2x.b83f4df.png', // img: 'https://www.tunnelbear.com/static/img/android@2x.b83f4df.png',
isOnline: false, // isOnline: false,
isOn: true, // isOn: true,
}, // },
{ // {
deviceName: 'Device 3', // deviceName: 'Device 3',
description: 'Lorem ipsum dolorsit amet,consectetur adipiscing elit. Cras sagitti.', // description: 'Lorem ipsum dolorsit amet,consectetur adipiscing elit. Cras sagitti.',
img: 'https://www.tunnelbear.com/static/img/android@2x.b83f4df.png', // img: 'https://www.tunnelbear.com/static/img/android@2x.b83f4df.png',
isOnline: true, // isOnline: true,
isOn: false, // isOn: false,
}, // },
{ // {
deviceName: 'Device 4', // deviceName: 'Device 4',
description: 'Lorem ipsum dolorsit amet,consectetur adipiscing elit. Cras sagitti.', // description: 'Lorem ipsum dolorsit amet,consectetur adipiscing elit. Cras sagitti.',
img: 'https://www.tunnelbear.com/static/img/android@2x.b83f4df.png', // img: 'https://www.tunnelbear.com/static/img/android@2x.b83f4df.png',
isOnline: false, // isOnline: false,
isOn: false, // isOn: false,
}, // },
]; ];
class SmartMeterScreen extends Component { class SmartMeterScreen extends Component {
...@@ -54,24 +56,49 @@ class SmartMeterScreen extends Component { ...@@ -54,24 +56,49 @@ class SmartMeterScreen extends Component {
), ),
}); });
componentDidMount() { state = {
/*----add listener willFocur,willBlur ---*/ initData: this.props.allDeviceInfo,
// const { navigation } = this.props; data: this.props.allDeviceInfo,
// this.blurListener = navigation.addListener('didBlur', () => { isLoading: true,
// console.log('didBlur'); };
// });
static getDerivedStateFromProps = (nextProps, prevState) => {
if (prevState.data !== nextProps.allDeviceInfo) {
return {
data: nextProps.allDeviceInfo,
};
} else null;
};
componentDidMount = async () => {
await this.props.getAllDeviceInfo();
};
componentDidUpdate = (prevProps, prevState) => {
if (prevState.data !== this.state.data) {
this.setState({ isLoading: false });
} }
};
render() { render() {
console.log(this.state);
let { allDeviceInfo, getAllDeviceInfo, setCurrentSelected } = this.props;
const { isLoading } = this.state;
return ( return (
<FlatList <FlatList
refreshing={isLoading}
onRefresh={getAllDeviceInfo}
style={[theme.container, theme.containerWithPadding]} style={[theme.container, theme.containerWithPadding]}
contentContainerStyle={{ paddingBottom: isIphoneX() ? 90 : 55 }} //iPhoneX BottomSpace = 34 contentContainerStyle={{ paddingBottom: isIphoneX() ? 90 : 55 }} //iPhoneX BottomSpace = 34
data={Meter} data={this.state.initData}
keyExtractor={item => item.deviceName} extraData={this.state.data}
keyExtractor={(item, index) => `Card${index}`}
ListEmptyComponent={() => ( ListEmptyComponent={() => (
<View> <View>
<Text style={[theme.normalText, { marginTop: 20 }]}>No Device Connected</Text> <Text style={[theme.normalText, { marginTop: 20 }]}>
{isLoading ? '' : 'No Device Connected'}
</Text>
</View> </View>
)} )}
ListHeaderComponent={() => ( ListHeaderComponent={() => (
...@@ -79,15 +106,15 @@ class SmartMeterScreen extends Component { ...@@ -79,15 +106,15 @@ class SmartMeterScreen extends Component {
)} )}
renderItem={({ item, index }) => ( renderItem={({ item, index }) => (
<MeterCard <MeterCard
key={index + item.deviceName} // key={`mastercard${index}`}
deviceName={item.deviceName} name={item.name || 'Untitled'}
description={item.description} description={item.description || ''}
img={item.img} img={item.img || null}
isOnline={item.isOnline} isOnline={item.isOnline || false}
isOn={item.isOn} isOn={item.isOn || false}
index={index + 1}
onPressEachCard={() => { onPressEachCard={() => {
this.props.navigation.navigate('SmartMeterDetail', { deviceName: item.deviceName }); setCurrentSelected(item.deviceId);
this.props.navigation.navigate('SmartMeterDetail', { name: item.name });
}} }}
/> />
)} )}
...@@ -96,4 +123,16 @@ class SmartMeterScreen extends Component { ...@@ -96,4 +123,16 @@ class SmartMeterScreen extends Component {
} }
} }
export default SmartMeterScreen; const mapStateToProps = state => ({
allDeviceInfo: state.allDataReducer.allDeviceInfo,
});
const mapDispatchToProps = {
getAllDeviceInfo,
setCurrentSelected,
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(SmartMeterScreen);
...@@ -13,6 +13,11 @@ class AuthLoadingScreen extends Component { ...@@ -13,6 +13,11 @@ class AuthLoadingScreen extends Component {
header: null, header: null,
}; };
constructor(props) {
super(props);
this._bootstrapAsync();
}
state = { state = {
isShowImg: true, isShowImg: true,
authentication: null, authentication: null,
...@@ -21,10 +26,10 @@ class AuthLoadingScreen extends Component { ...@@ -21,10 +26,10 @@ class AuthLoadingScreen extends Component {
showLogoThenIndicator = () => { showLogoThenIndicator = () => {
setTimeout(() => { setTimeout(() => {
this.setState({ isShowImg: false }); this.setState({ isShowImg: false });
}, 1300); }, 1200);
}; };
componentDidMount = async () => { _bootstrapAsync = async () => {
this.showLogoThenIndicator(); this.showLogoThenIndicator();
// Preload data from an external API // Preload data from an external API
// Preload data using AsyncStorage // Preload data using AsyncStorage
...@@ -34,7 +39,6 @@ class AuthLoadingScreen extends Component { ...@@ -34,7 +39,6 @@ class AuthLoadingScreen extends Component {
app.auth().onAuthStateChanged(async user => { app.auth().onAuthStateChanged(async user => {
if (user) { if (user) {
await this.props.getCurrentUser(); await this.props.getCurrentUser();
// await this.props.getAllDeviceId();
await this.props.getAllDeviceInfo(); await this.props.getAllDeviceInfo();
this.props.navigation.navigate(RememberedLogin ? 'Main' : 'Login'); this.props.navigation.navigate(RememberedLogin ? 'Main' : 'Login');
} else { } else {
...@@ -43,11 +47,35 @@ class AuthLoadingScreen extends Component { ...@@ -43,11 +47,35 @@ class AuthLoadingScreen extends Component {
}); });
}; };
// componentDidUpdate = (prevProps, prevState) => { // componentDidMount = async () => {
// this.showLogoThenIndicator();
// // Preload data from an external API
// // Preload data using AsyncStorage
// const alreadyLaunched = await AsyncStorage.getItem('alreadyLaunched');
// const RememberedLogin = await AsyncStorage.getItem('RememberedLogin');
// app.auth().onAuthStateChanged(async user => {
// if (user) {
// this.props.getCurrentUser && (await this.props.getCurrentUser());
// this.setState({ authentication: true });
// this.props.navigation.navigate(RememberedLogin ? 'Main' : 'Login');
// } else {
// this.setState({ authentication: false });
// this.props.navigation.navigate(alreadyLaunched ? 'Login' : 'Onboarding');
// }
// });
// };
// componentDidUpdate = async (prevProps, prevState) => {
// if (prevState.authentication !== this.state.authentication) { // if (prevState.authentication !== this.state.authentication) {
// this.state.authentication // this.props.getCurrentUser && (await this.props.getCurrentUser());
// ? this.props.navigation.navigate(RememberedLogin ? 'Main' : 'Login') // this.props.navigation.navigate(
// : this.props.navigation.navigate(alreadyLaunched ? 'Login' : 'Onboarding'); // this.state.RememberedLogin
// ? 'Main'
// : this.state.authentication || this.state.alreadyLaunched
// ? 'Login'
// : 'Onboarding'
// );
// } // }
// }; // };
...@@ -65,7 +93,6 @@ class AuthLoadingScreen extends Component { ...@@ -65,7 +93,6 @@ class AuthLoadingScreen extends Component {
) : ( ) : (
<ActivityIndicator size="large" color="#f44c4c" /> <ActivityIndicator size="large" color="#f44c4c" />
)} )}
{/* <StatusBar hidden /> */}
</View> </View>
); );
} }
......
...@@ -29,8 +29,8 @@ export default class LoginScreen extends Component { ...@@ -29,8 +29,8 @@ export default class LoginScreen extends Component {
success = async () => { success = async () => {
// console.log('call success function'); // console.log('call success function');
const alreadyLaunched = await AsyncStorage.getItem('alreadyLaunched'); // const alreadyLaunched = await AsyncStorage.getItem('alreadyLaunched');
if (alreadyLaunched !== null) await AsyncStorage.setItem('alreadyLaunched', 'true'); await AsyncStorage.setItem('alreadyLaunched', 'true');
// console.log('Remembered me?', this.state.isCheck); // console.log('Remembered me?', this.state.isCheck);
this.state.isCheck === true && (await AsyncStorage.setItem('RememberedLogin', 'true')); this.state.isCheck === true && (await AsyncStorage.setItem('RememberedLogin', 'true'));
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment