Skip to content
This repository was archived by the owner on Jul 19, 2019. It is now read-only.

Commit 765a63f

Browse files
committed
Add ids to data server-side so that keys can be used client-side
1 parent 55e01a9 commit 765a63f

File tree

3 files changed

+17
-6
lines changed

3 files changed

+17
-6
lines changed

comments.json

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
[
22
{
3+
"id": 1388534400000,
34
"author": "Pete Hunt",
45
"text": "Hey there!"
56
},
67
{
8+
"id": 1420070400000,
79
"author": "Paul O’Shannessy",
810
"text": "React is *great*!"
911
}

public/scripts/example.js

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,10 @@ var CommentBox = React.createClass({
4444
},
4545
handleCommentSubmit: function(comment) {
4646
var comments = this.state.data;
47+
// Optimistically set an id on the new comment. It will be replaced by an
48+
// id generated bu the server. In a production application you would likely
49+
// not use Date.now() for this and would have a more robust system in place.
50+
comment.id = Date.now();
4751
var newComments = comments.concat([comment]);
4852
this.setState({data: newComments});
4953
$.ajax({
@@ -79,12 +83,9 @@ var CommentBox = React.createClass({
7983

8084
var CommentList = React.createClass({
8185
render: function() {
82-
var commentNodes = this.props.data.map(function(comment, index) {
86+
var commentNodes = this.props.data.map(function(comment) {
8387
return (
84-
// `key` is a React-specific concept and is not mandatory for the
85-
// purpose of this tutorial. if you're curious, see more here:
86-
// http://facebook.github.io/react/docs/multiple-components.html#dynamic-children
87-
<Comment author={comment.author} key={index}>
88+
<Comment author={comment.author} key={comment.id}>
8889
{comment.text}
8990
</Comment>
9091
);

server.js

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,15 @@ app.get('/api/comments', function(req, res) {
3434
app.post('/api/comments', function(req, res) {
3535
fs.readFile(COMMENTS_FILE, function(err, data) {
3636
var comments = JSON.parse(data);
37-
comments.push(req.body);
37+
// NOTE: In a real implementation, we would likely rely on a database or
38+
// some other approach (e.g. UUIDs) to ensure a globally unique id. We'll
39+
// treat Date.now() as unique-enough for our purposes.
40+
var newComment = {
41+
id: Date.now(),
42+
author: req.body.author,
43+
text: req.body.text,
44+
};
45+
comments.push(newComment);
3846
fs.writeFile(COMMENTS_FILE, JSON.stringify(comments, null, 4), function(err) {
3947
res.setHeader('Cache-Control', 'no-cache');
4048
res.json(comments);

0 commit comments

Comments
 (0)