I want to share User's information for all screens of my app. (e.g. kind of similar to session in webapps). How can I achieve that in proper standard way in react-native.
So far, I have achieved this by keeping User's all information as a state in Main component and then passing Main Component's state as property on child components. Below is the shortened code for components-
var MainComponent = React.createClass({
getInitialState: function(){
return {
user: {
mobileNumber: "",
emailId:"",
},
userValidationStatus: false
};
},
_renderScene: function(){
switch(route.id){
case 1:
return <Screen1 navigator={navigator} parentState={this.state}/>
case 2:
return <Screen2 navigator={navigator} parentState={this.state} />
default:
return <Screen1 navigator={navigator} />
}
},
render: function(){
return (
<Navigator
initialRoute={{
id: 1,
title: 'someTitle'
}}
renderScene={this._renderScene}
navigator={this.props.navigator}
/>
);
}
});
var Screen1 = React.createClass({
render: function(){
return (
<View>
<TextInput
autoFocus='true'
onChangeText={(mobileNumber) => this.props.parentState.user.mobileNumber=mobileNumber}
value={this.state.mobileNumber}
/>
<TextInput
onChangeText={(emailId) => this.props.parentState.user.emailId=emailId}
value={this.state.emailId}
/>
</View>
);
}
});
var Screen2 = React.createClass({
render: function(){
return (
<View>
<TextInput
autoFocus='true'
onChangeText={(mobileNumber) => this.props.parentState.user.mobileNumber=mobileNumber}
value={this.state.mobileNumber}
/>
<TextInput
onChangeText={(emailId) => this.props.parentState.user.emailId=emailId}
value={this.state.emailId}
/>
</View>
);
}
});
Is this a proper way to achieve this? If no, What is the correct way to achieve such functionality.
You are correct in keeping the main state in the upper level (controller) component and passing data down as props.
Another way to do this and manage state across your application as it gets more complex is to use a library / ideology like Flux or Redux (an implementation of Flux).
There are quite a few tutorials available on the internet and in their documentation that should at least get you started. I would begin learning Flux before diving into Redux.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With