At the last stage of my project for learning react and firebase and I am facing a problem. From reading the docs of both of those I have understood how and what to do for the most part.
I want to take in the content from a blog post and then edit it and post it back using the
update()
method firebase has. As of now, the two errors I am facing are that I am unable to edit that content as react says that it is a controlled element which I understand from the docs is cause I passed in it as a value.
But when I tried to remove that and instead create a setState in an onInputChange like the docs suggested it gets updated but with blank content and the original text is missing as well from the input field. Which means it something I am doing wrong with react but I’m not sure what it is.
constructor(props){
super(props);
this.state = {
title: '',
body: '',
post:{},
};
this.onInputChange = this.onInputChange.bind(this);
this.onHandleUpdate = this.onHandleUpdate.bind(this);
}
componentDidMount(){
database.ref(`posts/${this.props.match.params.postId}`)
.on('value', snapshot => {
this.setState({post: snapshot.val()});
});
this.postId= this.props.match.params.postId;
}
onInputChange(e){
this.setState({
title: ‘’, body:''
});
}
onHandleUpdate(e){
console.log(this.postId);
e.preventDefault();
database.ref('posts').child(`${this.postId}`).update(this.state);
this.setState({
title: '',
body: ''
});
}
render() {
return (
<div className="container">
<form onSubmit={this.onHandleUpdate}>
<div className="form-group">
<input value={this.state.title && this.state.post.title} className="form-control" type="text" name="title" ref="title" onChange={this.onInputChange}/>
</div>
<br/>
<div className="form-group">
<input value={this.state.body && this.state.post.body} className="form-control" type="text" name="body" ref="body" onChange={this.onInputChange} />
<br/>
</div>
<button className="btn btn-success">Submit</button>
</form>
</div>
);
}
}
This is the how the code is set up at the moment. The summary of the problem simply comes down to why I am unable to change the value in the text box. What am I doing wrong please?