Getting this error when trying to add input from the web-application to the database. Struggeling to understad what the problem is. The error come when the button to insert to the database is used. Here's some of the code:
import React, { Component } from 'react';
import ProductService from './ProductService';
class Input extends Component {
constructor(props) {
super(props);
this.onChangeName = this.onChangeName.bind(this);
this.onChangeQuantity = this.onChangeQuantity.bind(this);
this.onChangePrice = this.onChangePrice.bind(this);
this.state = {
id: -1,
name: null,
quantity: null,
price: null
};
}
onChangeName(e) {
this.setState({
name: e.target.value
});
}
onChangeQuantity(e) {
this.setState({
quantity: e.target.value
});
}
onChangePrice(e) {
this.setState({
price: e.target.value
});
}
saveProduct() {
var data = {
name: this.state.name, //this is the line witch get the error
quantity: this.state.quantity,
price: this.state.price
};
ProductService.addProduct(data)
.then(response => {
this.setState({
id: response.data.id,
name: response.data.name,
quantity: response.data.quantity,
price: response.data.price
});
console.log(response.data);
})
.catch(e => {
console.log(e);
});
}
newProduct() {
this.setState({
name: "",
quantity: null,
price: null
});
}
render() {
return (
<div id="parent">
<form>
<p>Enter name:</p>
<input
type="text"
id="name"
required
value={this.state.name}
onChange={this.onChangeName}
name="name"
/>
</form>
<form>
<p>Enter price:</p>
<input
type="text"
id="price"
required
value={this.state.price}
onChange={this.onChangePrice}
name="price"
/>
</form>
<form>
<p>Enter quantity:</p>
<input
type="text"
id="quantity"
required
value={this.state.quantity}
onChange={this.onChangeQuantity}
name="quantity"
/>
</form>
<button onClick={this.saveProduct}>Enter in database</button>
</div>
);
}
}
export default Input;
When i change to for example:
saveProduct() {
var data = {
name: "test",
quantity: 123,
price: 456
};
Everything works. Ive tried diffrent things, but to me the error dont quite make sense. Anyone see where my mistake(s) are? Thank you in advance.
question from:
https://stackoverflow.com/questions/65942058/error-cannot-read-property-state-of-undefined-struggeling-to-get-frontend-to 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…