I'm performing edit/update operation but it give me the following error: TypeError: Cannot read property 'name' of null at editComponent.js :19
I'm attaching the code, can someone please help me.
import React,{Component} from 'react'
import axios from 'axios';
export default class EditComponent extends Component{
constructor() {
super()
this.state = {
name: "",
author: ""
}
this.handleChange = this.handleChange.bind(this)
this.submitHandleChange = this.submitHandleChange.bind(this)
}
componentDidMount() {
axios.get('localhost/book/edit'+this.props.match.params.id)
.then(response => {
this.setState({
name: response.data.name,
author: response.data.author
});
})
.catch(function (error) {
console.log(error);
})
}
handleChange(event) {
const {name, value} = event.target
this.setState({ [name]: value })
}
submitHandleChange(event){
event.preventDefault();
const book = {
name: this.state.name,
author: this.state.author
}
axios.post('localhost/book/update'+this.props.match.params.id, book)
.then(res => console.log(res.data));
this.props.history.push('/view');
}
render(){
return(
<div>
<h1> EditComponent </h1>
<form onSubmit={this.submitHandleChange}>
<input
type="text"
value={this.state.name}
name="name"
placeholder="First Name"
required
onChange={this.handleChange}
/>
<br />
<input
type="text"
value={this.state.author}
name="author"
placeholder="Last Name"
required
onChange={this.handleChange}
/>
<button >Submit</button>
</form>
</div>
)
}
}
Seems like there is no value 'name' in the response. try to
console.log(response) from axios
and see what it actually returns
Richard Uie
"Live and learn" should have been "LEARN or DIE."
It's wacky hard to diagnose this sort of thing without direct access to the live environment. That said, the error message reports, "TypeError: Cannot read property 'name' of null." That's not a complaint about a name property. It's telling you that the object you expect to have a name property is actually null...it has no properties, name or otherwise.
I'm guessin' that the response object returned by your call on axios.get() is null, and the response's name property is merely the first reference made to the response after get() returns.
Since I don't know anything about the library you're using, I don't know why a null response didn't spring an error state on you, but that's still my guess (from way over here, while blindfolded).