application-amicale/components/AuthenticatedScreen.js

111 lines
2.8 KiB
JavaScript
Raw Normal View History

2020-03-31 14:21:01 +02:00
import * as React from 'react';
import {View} from "react-native";
2020-03-31 18:40:06 +02:00
import {ActivityIndicator, Text, withTheme} from 'react-native-paper';
2020-03-31 14:21:01 +02:00
import ConnectionManager from "../managers/ConnectionManager";
type Props = {
navigation: Object,
theme: Object,
link: string,
renderFunction: Function,
}
type State = {
loading: boolean,
}
2020-03-31 18:40:06 +02:00
class AuthenticatedScreen extends React.Component<Props, State> {
2020-03-31 14:21:01 +02:00
state = {
loading: true,
};
2020-03-31 18:40:06 +02:00
currentUserToken: string;
2020-03-31 14:21:01 +02:00
connectionManager: ConnectionManager;
2020-03-31 18:40:06 +02:00
data: Object;
colors: Object;
2020-03-31 14:21:01 +02:00
constructor(props) {
super(props);
2020-03-31 18:40:06 +02:00
this.colors = props.theme.colors;
2020-03-31 14:21:01 +02:00
this.connectionManager = ConnectionManager.getInstance();
2020-03-31 18:40:06 +02:00
this.props.navigation.addListener('focus', this.onScreenFocus.bind(this));
this.fetchData();
}
onScreenFocus() {
if (this.currentUserToken !== this.connectionManager.getToken())
this.fetchData();
}
fetchData() {
if (!this.state.loading)
this.setState({loading: true});
2020-03-31 14:21:01 +02:00
this.connectionManager.isLoggedIn()
.then(() => {
this.connectionManager.authenticatedRequest(this.props.link)
.then((data) => {
2020-03-31 18:40:06 +02:00
this.onFinishedLoading(data);
2020-03-31 14:21:01 +02:00
})
.catch((error) => {
2020-03-31 18:40:06 +02:00
this.onFinishedLoading(undefined);
2020-03-31 14:21:01 +02:00
});
})
.catch(() => {
2020-03-31 18:40:06 +02:00
this.onFinishedLoading(undefined);
2020-03-31 14:21:01 +02:00
});
}
2020-03-31 18:40:06 +02:00
onFinishedLoading(data: Object) {
this.data = data;
this.currentUserToken = data !== undefined
? this.connectionManager.getToken()
: '';
this.setState({loading: false});
}
/**
* Gets the loading indicator
*
* @return {*}
*/
getRenderLoading() {
return (
<View style={{
backgroundColor: this.colors.background,
position: 'absolute',
top: 0,
right: 0,
width: '100%',
height: '100%',
flex: 1,
alignItems: 'center',
justifyContent: 'center'
}}>
<ActivityIndicator
animating={true}
size={'large'}
color={this.colors.primary}/>
</View>
);
}
getErrorRender() {
return <Text>ERROR</Text>;
}
2020-03-31 14:21:01 +02:00
render() {
return (
this.state.loading
2020-03-31 18:40:06 +02:00
? this.getRenderLoading()
: (this.data !== undefined
? this.props.renderFunction(this.data)
: this.getErrorRender())
2020-03-31 14:21:01 +02:00
);
}
}
2020-03-31 18:40:06 +02:00
export default withTheme(AuthenticatedScreen);