For this component I have two nested states.
And I have a text input with a submit button as shown in the code below.
I'd like to save user's input in this.state.schoolForm.userInput
whenever onChangeText fires, and then save this.state.schoolForm.userInput
to this.userInputs.schoolName
when commit button is clicked.
This would work when I just setState to this.state.userInputValue
(A simple not nested state) However, it wouldn't work when I try to setState to the nested state: this.state.schoolForm.userInput
When I click submit button nothing happens but it's supposed to transit to the next state. It seems like the way I save to a nested state is causing the problem but I have followed this post React setState for nested state and I can't find anything wrong from my code.
import React from 'react';
import { StyleSheet, Button, StatusBar, Text, TextInput, View} from 'react-native';
const states = {
schoolForm: {
prompt: "Where did you go to school?",
userInput: "School name",
},
durationForm: {
prompt: "For how long?",
userInput: "Duration",
},
}
export default class NewEducation extends React.Component {
constructor(props) {
super(props);
this.state = {
//form: states.reviewForm,
form: states.schoolForm,
userInputs: {
schoolName: "",
duration: ""
},
//for testing
userInputValue: "",
}
}
_nextState = () => {
switch(this.state.form) {
case states.schoolForm:
this.setState({form:states.durationForm});
break;
case states.durationForm:
this.setState({form:states.degreeForm});
break;
default:
break;
}
}
_submitInfo = () => {
switch(this.state.form) {
case states.schoolForm:
//this.setState({ userInputs: { ...this.state.userInputs, schoolName: this.state.form.userInput} });
this.setState({ userInputs: { ...this.state.userInputs, schoolName: this.state.userInputValue}});
break;
case states.durationForm:
//this.setState({ userInputs: { ...this.state.userInputs, duration: this.state.form.userInput} });
this.setState({ userInputs: { ...this.state.userInputs, duration: this.state.userInputValue}});
break;
default:
break;
}
this._nextState();
}
render() {
return (
<View style={styles.container}>
<StatusBar barStyle="light-content"/>
<Text style={styles.textContentWhite}>{this.state.form.prompt}</Text>
<TextInput
style={styles.textContentWhite}
placeholder={this.state.form.userInput}
placeholderTextColor="#B7BEDE"
onChangeText={(userInputValue) =>
//this.setState({ form: {userInput: userInputValue} }
this.setState({form: { ...this.state.form, userInput: userInputValue }}
)}
/>
<Button
onPress={this._submitInfo}
title="Submit"
color="white"
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
backgroundColor: "black",
},
textContentWhite: {
fontSize: 20,
color: 'white',
},
});