CODE:
getInitialState: function() {
return {
name: "",
ingredients: ""
}
},
handleSubmit: function() {
var newRecipe = {
name: this.state.name,
ingredients: this.state.ingredients
};
this.props.handleAdd(newRecipe);
this.handleClose();
},
handleNameChange: function () {
this.setState({
name: event.target.value
});
},
handleIngredientsChange: function () {
this.setState({
ingredients: event.target.value
});
},
render: function () {
return (
<div>
<h3>Name</h3>
<input value={this.state.name} onChange={this.handleNameChange}></input>
<h3>Ingredients</h3>
<textarea value={this.state.ingredients} onChange={this.handleIngredientsChange}></textarea>
</div>
)
}
SITUATION:
this.state.name
is undefined
. Why ?
It must have something to do with my current implementation of setState ?
I am learning React, so there may be a few obvious mistakes.
CODE:
getInitialState: function() {
return {
name: "",
ingredients: ""
}
},
handleSubmit: function() {
var newRecipe = {
name: this.state.name,
ingredients: this.state.ingredients
};
this.props.handleAdd(newRecipe);
this.handleClose();
},
handleNameChange: function () {
this.setState({
name: event.target.value
});
},
handleIngredientsChange: function () {
this.setState({
ingredients: event.target.value
});
},
render: function () {
return (
<div>
<h3>Name</h3>
<input value={this.state.name} onChange={this.handleNameChange}></input>
<h3>Ingredients</h3>
<textarea value={this.state.ingredients} onChange={this.handleIngredientsChange}></textarea>
</div>
)
}
SITUATION:
this.state.name
is undefined
. Why ?
It must have something to do with my current implementation of setState ?
I am learning React, so there may be a few obvious mistakes.
Share Improve this question edited Apr 17, 2017 at 18:01 Coder1000 asked Apr 17, 2017 at 17:59 Coder1000Coder1000 4,49110 gold badges37 silver badges87 bronze badges 2- where you checking state value? – Ved Commented Apr 17, 2017 at 18:01
- @Ved Code updated. – Coder1000 Commented Apr 17, 2017 at 18:02
2 Answers
Reset to default 4I think the problem is missing event
argument for handleNameChange
and handleIngredientsChange
methods :
handleNameChange: function () {
this.setState({
name: event.target.value
});
},
Try changing it to:
handleNameChange: function (event) {
this.setState({
name: event.target.value
});
},
because in your initial method, event
is undefined, so it sets your state to undefined
too.
The same is available for this handleIngredientsChange
, change it to:
handleIngredientsChange: function (event) {
this.setState({
ingredients: event.target.value
});
},
- Store state into a ref(useRef)
- Then define ref.current = state_name ref.current always get current updated state