I have this AddUser component which which is a simple componnet that gets an email address, and a role from dropdownlist and then passes these two values to the parent component. Everything works fine other than one thing: if I first enter the email address and then choose the role it onChange() doesn't get the value from dropdownlist and pass null to the parent component. But if I first choose role and then enter the email, onChange() gets both values! How can I fix it?
This component has 3 props: roles is a dictionary and I'm creating rolesListfrom it to use it as data for DropdownList (it's from react-widget, https://jquense.github.io/react-widgets/docs/#/?_k=3fo3eq). The second prop is handleChange() that set the states of the parent component. the 3th one ishandleAddNewUser() that returns the values from form to the parent component.
export const AddUser = React.createClass({
getInitialState() {
return {
email: "",
selectedRole: "",
};
},
onChange() {
var email = this.email.value;
this.props.handleChange(email, this.state.selectedRole);
},
render() {
var rolesList = [];
for(var key in this.props.roles){
rolesList.push(key);
}
return(
<div >
<form onSubmit={this.props.handleAddNewUser}>
<label >New user email address:</label>
<input ref={(ref) => this.email = ref} name='email' type='email' onChange={this.onChange} required />
<label >Choose a role for new user:</label>
<DropdownList data={rolesList} value={this.state.selectedRole} name='rolesList' onChange={selectedRole => this.setState({ selectedRole })} />
<button type="submit" >Add user</button>
</form>
</div>
);
},
});
UPDATE: this is the code from parent component, handleChange() sets the states for parent component. handleAddNewUser() is supposed to use the states and make an ajax request to create new user. Right now it gets value for newUserEmail but not the newUserRole
handleChange(email, selectedRole){
this.setState({newUserEmail: email})
this.setState({newUserRole: selectedRole})
},
handleAddNewUser(e) {
e.preventDefault();
// using its state, it supposed to make an ajax request and create a new user
}