dimanche 20 octobre 2019

reactjs: how to show updated state immediately?

I am trying to update the number of likes(with like-unlike button, methods = [POST, DELETE, GET]) and comments(form, methods = [POST, GET]). My like button changes on click immediately but the number of likes is not updating. Clicking on the like-unlike button is not sending any POST or DELETE request.

  constructor(props) {
    // Initialize mutable state
    super(props);
    this.state = { num_likes: 0, logname_likes_this: false };
    this.handleClick = this.handleClick.bind(this);
  }

  componentDidMount() {
    // Call REST API to get number of likes
    fetch(this.props.url, { credentials: 'same-origin' })
      .then((response) => {
        if (!response.ok) throw Error(response.statusText);
        return response.json();
      })
      .then((data) => {
        this.setState({
          num_likes: data.likes_count,
          logname_likes_this: data.logname_likes_this,
        });
      })
      .catch(error => console.log(error));
  }

  handleClick() {
    this.setState(state => ({
      logname_likes_this: !this.state.logname_likes_this
    }));
  }

  render() {

    const liked = this.state.logname_likes_this
    let button;

    if (liked) {
      button = <button onClick={this.handleClick} className="like-unlike-button" name="unlike">unlike</button>
    } else {
      button = <button onClick={this.handleClick} className="like-unlike-button" name="like">like</button>
    }

    // Render number of likes
    return (
      <div className="likes">
        <p>{this.state.num_likes} like{this.state.num_likes !== 1 ? 's' : ''}</p>

        {button}
      </div>
    );
  }
}

How I delete likes from the database. But clicking on the like-unlike button is not sending any POST or DELETE request...

@app.route('/api/v1/p/<int:postid_url_slug>/likes/', methods=["DELETE"])
def delete_likes(postid_url_slug):
    if "username" not in flask.session:
        context = {
          "message": "Forbidden",
          "status_code": 403
        }
        return flask.jsonify(**context), 403

    db = insta485.model.get_db()
    logged_in_user = flask.session["username"]
    query = "DELETE FROM likes WHERE postid = ? AND owner = ?"

    db.execute(query, (postid_url_slug, logged_in_user))

    return "", 204

For adding likes:

@app.route('/api/v1/p/<int:postid_url_slug>/likes/', methods=["POST"])
def add_likes(postid_url_slug):
query = "INSERT INTO likes(owner, postid, created) VALUES(?, ?, DATETIME('now'))"

        db.execute(query, (logged_in_user, postid_url_slug))

        context = {
            "logname": logged_in_user,
            "postid": postid_url_slug

        }
        return flask.jsonify(**context), 201



Aucun commentaire:

Enregistrer un commentaire