I am creating a blog using React, MongoDB, Express and Node. I have three components: App, List, and Item. The item is a blog post; the list is a list of the blog posts, and the app includes a place to enter text and submit it. I will eventually add more functionality, but I want to determine if I am adhering to best practices for React (I doubt I am).
So in App, I getInitialState with an array of posts (posts) and a string of text for the input (postbody). I used the componentDidMount to make an AJAX GET request to my database, so the user can see all the posts.
To handle entering text I just made a simple handleChange function which updates the state of postbody.
I also have a handleClick function, which grabs this.state.postbody and then POSTs it database. However the same function also makes a separate GET request of the database to update the state of the posts array. This doesn't seem right! Shouldn't that be handled some other way and updated automatically? * This is the primary question I have. *
Also, please let me know if I need to break the components down further, or if I am violating best practices using React (e.g. changing state in the wrong place, or using props incorrectly).
var React = require('react');
var Item = React.createClass({
render: function() {
return (
<div>
<h2>{this.props.postbody}</h2>
</div>
)
}
})
var List = React.createClass({
render: function() {
return (
<div>
{this.props.array.map(function(post) {
return (
<Item postbody={post.postbody}></Item>
)
})}
</div>
)
}
})
var App = React.createClass({
getInitialState: function() {
return {
posts: [],
postbody: ''
}
},
componentDidMount: function() {
$.ajax({
type: 'GET',
url: '/api/blogPosts',
success: function(data) {
this.setState({posts: data});
}.bind(this)
})
},
handleClick: function() {
event.preventDefault();
var blogPost = this.state.postbody;
$.ajax({
type: 'POST',
url: '/api/blogPosts',
data: { postbody: blogPost }
});
$.ajax({
type: 'GET',
url: '/api/blogPosts',
success: function(data) {
this.setState({posts: data});
}.bind(this)
})
},
handleChange: function(event) {
this.setState({ postbody: event.target.value})
},
render: function() {
return (
<div>
<form action="/api/blogPosts" method="post">
<input onChange={this.handleChange} type="text" name="postbody"></input>
<button type="button" onClick={this.handleClick}>Submit</button>
</form>
<List array={this.state.posts} />
</div>
)
}
})