{"size": 1244, "ext": "js", "max_stars_repo_path": "src/raw/components/story.js", "max_stars_repo_name": "ForbesLindesay/react-data-fetching-demo", "max_stars_repo_stars_event_min_datetime": "2016-06-07T07:49:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-07T14:07:48.000Z", "max_issues_repo_path": "src/raw/components/story.js", "max_issues_repo_name": "ForbesLindesay/react-data-fetching-demo", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/raw/components/story.js", "max_forks_repo_name": "ForbesLindesay/react-data-fetching-demo", "max_forks_repo_forks_event_min_datetime": "2016-06-09T09:41:18.000Z", "max_forks_repo_forks_event_max_datetime": "2016-06-09T09:41:18.000Z"}
{"max_stars_count": 70, "max_issues_count": null, "max_forks_count": 1, "avg_line_length": 25.387755102, "max_line_length": 66, "alphanum_fraction": 0.5795819936}
import React, {Component} from 'react';
import request from 'then-request';
import Spinner from './spinner';

class Story extends Component {
  constructor() {
    super();
    this.state = {loading: true, story: null};
    this._onVote = this._onVote.bind(this);
  }
  componentDidMount() {
    request('get', '/api/stories/' + this.props.id)
    .getBody('utf8').then(JSON.parse).done(
      story => this.setState({loading: false, story})
    );
  }
  _onVote() {
    // Optimistic update
    this.setState({
      story: {
        ...this.state.story,
        votes: this.state.story.votes + 1,
      },
    });
    // actual update
    request('post', '/api/stories/' + this.props.id + '/vote')
    .getBody('utf8').then(JSON.parse).done(
      result => {
        this.setState({loading: false, story: result.story});
        this.props.onUpdateOrder();
      }
    );
  }
  render() {
    if (this.state.loading) return <Spinner />;
    return (
      <article>
        <span className="vote-count">
          {this.state.story.votes}
        </span>
        <div className="story-body">{this.state.story.body}</div>
        <button type="button" onClick={this._onVote}>Vote</button>
      </article>
    );
  }
}

export default Story;
