|
| 1 | +import React from 'react'; |
| 2 | +import Immutable from 'immutable'; |
| 3 | +import request from 'axios'; |
| 4 | +import CommentForm from './CommentForm'; |
| 5 | +import CommentList from './CommentList'; |
| 6 | +import metaTagsManager from '../utils/metaTagsManager'; |
| 7 | + |
| 8 | +const SimpleCommentScreen = React.createClass({ |
| 9 | + displayName: 'SimpleCommentScreen', |
| 10 | + |
| 11 | + getInitialState() { |
| 12 | + return { |
| 13 | + $$comments: Immutable.fromJS([]), |
| 14 | + ajaxSending: false, |
| 15 | + fetchCommentsError: null, |
| 16 | + submitCommentError: null, |
| 17 | + }; |
| 18 | + }, |
| 19 | + |
| 20 | + componentDidMount() { |
| 21 | + this.fetchComments(); |
| 22 | + }, |
| 23 | + |
| 24 | + fetchComments() { |
| 25 | + return request.get('comments.json', { responseType: 'json' }) |
| 26 | + .then(res => this.setState({ $$comments: Immutable.fromJS(res.data) })) |
| 27 | + .catch(error => this.setState({ fetchCommentsError: error })); |
| 28 | + }, |
| 29 | + |
| 30 | + handleCommentSubmit(comment) { |
| 31 | + this.setState({ ajaxSending: true }); |
| 32 | + |
| 33 | + const requestConfig = { |
| 34 | + responseType: 'json', |
| 35 | + headers: { |
| 36 | + 'X-CSRF-Token': metaTagsManager.getCSRFToken(), |
| 37 | + }, |
| 38 | + }; |
| 39 | + |
| 40 | + return request.post('comments.json', { comment }, requestConfig) |
| 41 | + .then(() => { |
| 42 | + const { $$comments } = this.state; |
| 43 | + const $$comment = Immutable.fromJS(comment); |
| 44 | + |
| 45 | + this.setState({ |
| 46 | + $$comments: $$comments.push($$comment), |
| 47 | + ajaxSending: false, |
| 48 | + }); |
| 49 | + }) |
| 50 | + .catch(error => { |
| 51 | + this.setState({ |
| 52 | + submitCommentError: error, |
| 53 | + ajaxSending: false, |
| 54 | + }); |
| 55 | + }); |
| 56 | + }, |
| 57 | + |
| 58 | + render() { |
| 59 | + return ( |
| 60 | + <div className="commentBox container"> |
| 61 | + <h2>Comments</h2> |
| 62 | + <p> |
| 63 | + Text take Github Flavored Markdown. Comments older than 24 hours are deleted. |
| 64 | + <b> Name</b> is preserved, <b>Text</b> is reset, between submits. |
| 65 | + </p> |
| 66 | + <CommentForm |
| 67 | + ajaxSending={this.state.ajaxSending} |
| 68 | + actions={{ submitComment: this.handleCommentSubmit }} |
| 69 | + error={this.state.submitCommentError} |
| 70 | + /> |
| 71 | + <CommentList |
| 72 | + $$comments={this.state.$$comments} |
| 73 | + error={this.state.fetchCommentsError} |
| 74 | + /> |
| 75 | + </div> |
| 76 | + ); |
| 77 | + }, |
| 78 | +}); |
| 79 | + |
| 80 | +export default SimpleCommentScreen; |
0 commit comments