Reputation: 155
I'm trying to save some basic user info (name, address, phone number, etc.) with AsyncStorage.
I want to store this information in an object like so:
user: {
complete: '',
fname: '',
lname: '',
email: '',
phone: '',
street: '',
city: '',
state: '',
zip: '',
phone: ''
}
I have a simple page with a textbox and a button to test this out. the textbox will be for inputting the "fname" value of my user object, and the button just submits it to asyncStorage:
export default class UserInfo extends React.Component {
static navigationOptions = {
title: "Coming soon!"
};
state = {
user: {
complete: '',
fname: '',
lname: '',
email: '',
phone: '',
street: '',
city: '',
state: '',
zip: '',
phone: ''
},
isLoading: true
}
componentDidMount = () => AsyncStorage.getItem('user').then((value) => this.setState({ 'user': value, isLoading: false}))
setUser = (value) => {
AsyncStorage.setItem('user', value);
}
render() {
if(this.state.isLoading) {
return (<ActivityIndicator/>)
}
return (
<View>
<TextInput
style={{height: 40, borderColor: 'gray', borderWidth: 1}}
onChangeText={(text) => this.state.user.fname}/>
<Button title="submit" onPress = {() => {this.setUser(this.state.user)}}/>
</View>
);
}
}
Unfortunately, I seem to get snagged on this line:
onChangeText={(text) => this.state.user.fname}/>
I get the following error:
null is not an object (evaluating '_this2.state.user.fname')
I'm not sure where I'm going wrong here, I had no issue storing simple strings in asyncStorage, but trying to write to an object in state is giving me trouble.
Can someone point me in the right direction here?
Thanks.
Upvotes: 0
Views: 2019
Reputation: 3150
Use it as:
export default class UserInfo extends React.Component {
static navigationOptions = {
title: "Coming soon!"
};
state = {
user: {
complete: '',
fname: '',
lname: '',
email: '',
phone: '',
street: '',
city: '',
state: '',
zip: '',
phone: ''
},
isLoading: true
}
componentDidMount = () => AsyncStorage.getItem('user').then((value) => this.setState({ 'user': value, isLoading: false}))
setUser = () => {
this.setState({user:this.state.user},()=>{
AsyncStorage.setItem('user', this.state.user);
})
}
render() {
if(this.state.isLoading) {
return (<ActivityIndicator/>)
}
return (
<View>
<TextInput
style={{height: 40, borderColor: 'gray', borderWidth: 1}}
onChangeText={(text) => this.state.user.fname}/>
<Button title="submit" onPress = {() => {this.setUser()}}/>
</View>
);
}
}
Upvotes: 1
Reputation: 5186
You cannot directly update the state as you code. You need to grab the object from state, then update its value and then you store object into state again. Below is the correct answer:
onChangeText={(text) => {
let user = this.state.user
user.fname = text
this.setState({
user
})
}}/>
Upvotes: 0