I am a react-native and javascript newbie. Once I understand how to initialize storage parameters to default values, I plan to integrate with my existing redux reducer.
'use strict';
import React, {
AppRegistry,
Component,
StyleSheet,
Text,
View
} from 'react-native';
import Storage from 'react-native-storage';
var storage = new Storage({
size: 1000,
defaultExpires: 1000 * 3600 * 24,
enableCache: true,
sync : {
}
});
class reactnativestoragetest extends Component {
constructor(props) {
super(props);
this.state = {
gpsEnabled: false,
unitType: -1,
};
this.storageLoad.bind(this);
this.storageLoaded.bind(this);
this.storageInitDefaults.bind(this);
this.render.bind(this);
}
// Is this the wrong place to do this?
componentWillMount() {
this.storageInitDefaults();
this.storageLoad();
}
// Load my app settings
storageLoad(ret) {
storage.load({
key: 'appSettings',
autoSync: true,
syncInBackground: true
}).then( ret => this.storageLoaded(ret)
).catch( err => {
// Exception is thrown the 1st time app is run *if* storage.save had not been called
console.warn('** Error: ', err);
})
}
// found data - Why does changing state here not call render() ?
storageLoaded(ret) {
console.log('*** storageLoaded ***');
console.log('ret.gpsEnabled:', ret.gpsEnabled);
console.log('ret.unitType:', ret.unitType);
this.state = {
gpsEnabled: ret.gpsEnabled,
unitType: ret.unitType,
};
}
// When app is run for first time, need to init my app settings
storageInitDefaults(ret) {
console.log('*** storageInitDefaults ***');
storage.save({
key: 'appSettings', // Note: Do not use underscore("_") in key!
rawData: {
gpsEnabled: true,
unitType: 2,
},
expires: 1000 * 3600
});
}
// How to make render be called after storageLoaded() receives the data?
render() {
console.log('*** render ***');
return (
<View style={styles.container}>
<Text style={styles.welcome}>
https://www.npmjs.com/package/react-native-storage
</Text>
<Text style={styles.instructions}>
gpsEnabled: {this.state.gpsEnabled.toString()}
</Text>
<Text style={styles.instructions}>
unitType: {this.state.unitType.toString()}
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('reactnativestoragetest', () => reactnativestoragetest);