Nick Bolsh
Nick Bolsh

Reputation: 150

Return error message in React

I'm learning ReactJS. I'm looking the tutorial - http://facebook.github.io/react/docs/tutorial.html

On submit the script read JSON from the server:

handleCommentSubmit: function(comment) {
    var comments = this.state.data;
    comments.push(comment);
    this.setState({data: comments}, function() {
      // `setState` accepts a callback. To avoid (improbable) race condition,
      // `we'll send the ajax request right after we optimistically set the new
      // `state.
      $.ajax({
        url: this.props.url,
        dataType: 'json',
        type: 'POST',
        data: comment,
        success: function(data) {
          this.setState({data: data});
        }.bind(this),
        error: function(xhr, status, err) {
          console.error(this.props.url, status, err.toString());
        }.bind(this)
      });
    });
  },

And update data. How can I send error message from JSON? Something like this:

<Comment author={comment.author} key={index}>
    {comment.text}
    <div class="error">Error</div>
</Comment>

Should I set it in data: this.setState({[{name: 'John', text: 'text', error: 'error'}]});

And change comments?:

<Comment author={comment.author} key={index}>
    {comment.text}
    <div class="error">{comment.error}</div>
</Comment>

Upvotes: 2

Views: 10120

Answers (1)

Miles
Miles

Reputation: 283

From what I see here, the error returned would be request-specific, not comment-specific. In that paradigm it wouldn't make sense to give each comment an error property. Instead, in this situation I'd keep some sort of array to store the errors:

this.setState({
  errors: this.errors.push(err);
});

Then you can have a separate <ErrorDisplay/> component of your own creation which receives the error array as a prop. Whenever the array changes, perhaps it can display the most recent error for a few seconds. It's up to you.

By the way, dig into Flux as soon as you can. If not Flux, then something else. The folks at Facebook will eagerly tell you that keeping definitive state like this in a React component is to be avoided. It's a necessary evil when getting acquainted with React though, so don't worry.

Upvotes: 2

Related Questions