Skip to content

Instantly share code, notes, and snippets.

@geirman
Created October 27, 2015 23:51
Show Gist options
  • Save geirman/1901d4b1bfad42ec6d65 to your computer and use it in GitHub Desktop.
Save geirman/1901d4b1bfad42ec6d65 to your computer and use it in GitHub Desktop.
'use strict';
var React = require('react-native');
var GLOBAL = require('../Globals');
var Swipeout = require('react-native-swipeout');
var Separator = require('./Separator');
var Api = require('../Utils/Api');
var TrackedItemIndex = require('./TrackedItemIndex');
var {
ActivityIndicatorIOS,
AsyncStorage,
ListView,
StyleSheet,
Text,
TouchableHighlight,
View,
} = React;
class AircraftList extends React.Component{
constructor(props){
super(props);
this.ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
this.state = {
dataSource: this.ds.cloneWithRows(this.props.aircraft_list.aircraft),
isLoading: false,
showingCache: false,
};
}
_renderHeader(){
return(
<ActivityIndicatorIOS
style={styles.activityIndicator}
animating={this.state.isLoading}
color={GLOBAL.COLOR.ORANGE}
size="large" />
)
}
_renderRow( aircraft ){
let aircraft_id = aircraft.reg_number;
// TODO: Get the dateCached
let dateCached = 'date goes here'; // DOESN'T WORK >> AsyncStorage.getItem(aircraft_id).then(data => JSON.parse(data).cachedOn);
var swipeoutBtns = [
{
text: 'Clear Cache',
color: '#fff',
backgroundColor: '#c00',
type: 'secondary',
onPress: function(){this._clearCache( aircraft_id )}.bind(this),
},
// {
// text: 'Refresh Cache',
// color: '#fff',
// backgroundColor: '#060',
// type: 'primary',
// onPress: function(){this._refreshCache( aircraft_id )}.bind(this),
// },
]
return (
<Swipeout
right={swipeoutBtns}
autoClose='true'
backgroundColor= 'transparent'>
<TouchableHighlight
underlayColor='white'
onPress={() => { this._handleTap( aircraft_id ) }}>
<View>
<View style={styles.rowContainer}>
<View style={styles.countContainer}>
<Text style={styles.count}>
{aircraft.ti_count}
</Text>
<Text style={styles.countLabel}>
TI&apos;s
</Text>
</View>
<View style={styles.aircraftContainer}>
<Text style={styles.aircraft}>
{aircraft_id}
</Text>
<Text style={styles.cacheLabel}>
last updated: {dateCached}
</Text>
</View>
</View>
<Separator />
</View>
</TouchableHighlight>
</Swipeout>
)
}
_clearCache( aircraft_id ){
// TODO: add toast-like feedback to confirm the action
AsyncStorage.removeItem(aircraft_id);
console.log('cache deleted for '+ aircraft_id);
}
// Unused because clicking on the menu item will refresh the cache anyway
// _refreshCache( aircraft_id ){
// this._getTrackedItems( aircraft_id );
// console.log('cache refreshed for '+ aircraft_id);
// }
_handleTap( aircraft_id ){
this.setState({
isLoading: true,
});
Api.getTrackedItems( aircraft_id )
.then((jsonRes) => this._handleResponse(jsonRes))
.catch((warning) => {
console.warn('WARN: unable to retrieve aircraft details from the network, so attempting to grab cache instead...', warning.message);
// TODO: Move AsyncStorage call to _getCache()
AsyncStorage.getItem( aircraft_id )
.then( data => {
this.setState({
isLoading: false,
showingCache: true,
})
if(!data){
console.info('INFO: there were no detail cached data for aircraft...', aircraft_id);
}else{
this._handleResponse(JSON.parse(data));
}
})
.catch(error => console.error('ERROR: unable to retrieve cached details for aircraft '+ aircraft_id +' because...', error.message))
.done();
})
}
_handleResponse(aircraft_object){
this.setState({
isLoading: false,
})
if(!this.state.showingCache){
this._setCache(aircraft_object);
}
this.props.navigator.push({
title: 'TI Lookup',
component: TrackedItemIndex,
passProps: {aircraft_object: aircraft_object}
});
}
_setCache(aircraft_object){
let aircraft_id = aircraft_object.aircraft.reg_number;
console.log('SUCCESS: aircraft details retrieved from the network and cached for aircraft...', aircraft_id);
aircraft_object.cachedOn = new Date();
this._setCachedOn(aircraft_id, aircraft_object.cachedOn);
AsyncStorage.setItem(aircraft_id, JSON.stringify(aircraft_object));
}
_getCache( aircraft_id ){
/*
When I move the AsyncStorage function here (lines 123:136), I get nothing
but `undefined` returned back to the calling function. Probably because
`undefined` is returned faster than the promise.
*/
}
_setCachedOn( aircraft_id, timestamp ){
AsyncStorage.getItem( this.props.user_id )
.then((list) => {
// go through each aircraft object looking for the one that contains
// the aircraft_id, then add the key cachedOn with a value of timestamp
list = JSON.parse(list);
for(let i = 0; i < list.aircraft.length; i++){
if(aircraft_id === list.aircraft[i].reg_number){
// add the timestamp then save it back
list.aircraft[i].cachedOn = timestamp;
AsyncStorage.setItem(this.props.user_id, JSON.stringify(list));
}
}
})
}
render(){
return(
<View style={styles.container}>
<ListView
dataSource={this.state.dataSource}
renderRow={this._renderRow.bind(this)}
renderHeader={this._renderHeader.bind(this)} />
</View>
);
}
};
var styles = StyleSheet.create({
container: {
flex: 1,
},
rowContainer: {
paddingVertical: 10,
flexDirection: 'row',
},
countContainer: {
paddingVertical: 5,
paddingHorizontal: 10,
},
count: {
color: GLOBAL.COLOR.ORANGE,
fontSize: 20,
},
countLabel: {
color: GLOBAL.COLOR.DARKGRAY,
fontSize: 10,
},
aircraftContainer: {
paddingVertical: 5,
paddingHorizontal: 10,
},
aircraft: {
color: GLOBAL.COLOR.ORANGE,
fontSize: 20,
},
cacheLabel: {
color: GLOBAL.COLOR.DARKGRAY,
fontSize: 10,
},
activityIndicator: {
alignSelf: 'center',
},
});
AircraftList.propTypes = {
aircraft_list: React.PropTypes.object.isRequired,
user_id: React.PropTypes.string.isRequired,
}
module.exports = AircraftList;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment