I'm attempting to update the state of a Parent
component after the user updates the value of a Child
component's select
element.
Whilst I've got it somewhat working, I've noticed that when I fire the onChange
event on my select
, it will always return the previous value instead of the value that has just been selected.
class Parent extends Component{
constructor(props){
super(props);
this.state = { data: {
condition: "any"
}};
}
update = data => {
this.setState({ data: {
...this.state.data,
...data
}});
// This gets called every time I change the value of my select element.
console.log(this.state.data);
}
render(){
return (
<Child
condition={this.state.data.condition}
onUpdate={data => this.update(data)} />
);
}
}
class Child extends Component{
updateParent = data => {
this.props.onUpdate(data);
}
render(){
const options = [
["any", "Any Condition"],
["new", "Brand New"],
["used", "Used"]
];
return (
<select
defaultValue={ props.selected }
onChange={({ target }) => this.updateParent({ condition: target.value })}>
{ options.map(([id, name]) => (
<option key={id} value={id}>{ name }</option>
)}
</select>
);
}
}
In this example, if I select used
, the console will return any
. Then, if I select new
, the console will return used
.