Browse Source

Listing 21: adding comments - optimistic updating.

Frederic G. MARAND 8 years ago
parent
commit
16f42c90cb
1 changed files with 11 additions and 0 deletions
  1. 11 0
      public/scripts/tutorial.js

+ 11 - 0
public/scripts/tutorial.js

@@ -87,6 +87,15 @@ let CommentBox = React.createClass({
     return { data: [] };
   },
   handleCommentSubmit: function (comment) {
+    let comments = this.state.data;
+    // Optimistically set an id on the new comment. It will be replaced by an
+    // id generated on the server. In a production application, you would likely
+    // not use Date.now() for this and would have a more robust system in place.
+    comment.id = Date.now();
+    let newComments = comments.concat([comment]);
+    // Assume all will go well.
+    this.setState({ data: newComments });
+
     $.ajax({
       url: this.props.url,
       dataType: "json",
@@ -96,6 +105,8 @@ let CommentBox = React.createClass({
         this.setState({ data: data });
       }.bind(this),
       error: function (xhr, status, err) {
+        // Restore the original comment state since the new state could not be applied.
+        this.setState({data: comments });
         console.error(this.props.url, status, err.toString());
       }
     });