Skip to content
Advertisement

Auto update when onSubmit with ReactJS

I have an app that post/get data from json. However when I add a comment, the latest comment that I added did not append automatically, but it will show if i refresh or reinstate the values.

Here’s the code that handles my comments

handleCommentChange(e) {
    this.setState({text: e.target.value});
  }

  handleComment(e) {
    e.preventDefault();
    var callback = console.log('lol');
    Request.post('http://localhost:3000/api/comments')
           .send({
            idComment: this.state.id,
            author: this.state.name,
            text: this.state.text
          })
           .end(callback)
           this.ReturnComment();

    var newItem = {
      id: Date.now(),
      author: this.state.name,
      text: this.state.text
    };
    // this.setState((prevState) => ({
    //   items: prevState.items.concat(newItem),
    //   text: ""
    // }));
    this.setState({
      text: ""
    });
  }



  ReturnComment(){
    var urlComment = "http://localhost:3000/api/comments";
    Request.get(urlComment)
            .then((i) => {this.setState({commentBody: i})});
  }

And this is the component that uses those functions

export default React.createClass ({

  render() {
    return (

      <div>
        <h1>Comments <small>on {this.props.pokeName}</small></h1>
        <div className="commentsSection">
          <div>
            <div>
                {this.props.commentBody.body
                  .filter((objComment) => {return objComment.author === this.props.pokeName})
                  .map((i) => {return (
                                <div className="itemComment">
                                  <p className="no-margin">"{i.text}"</p>
                                  <p className="right">-{i.id}</p>
                                </div>)
                              })
                }
                 {this.props.items.map(item => (
                    <div className="itemComment">
                      <p className="no-margin" key={item.id}>"{item.text}"</p>
                      <p className="right">-{item.id}</p>
                    </div>
                ))}
            </div>
                 
          </div>
        </div>
        <form onSubmit={this.props.handleComment}>
          <textarea className="textarea" onChange={this.props.onChange} value={this.props.text} rows="4"/>
          <button className="btn btn-default">Comment</button>
        </form>
      </div>
    );
  }
}

  )

Advertisement

Answer

It is because, inside handleComment, you are calling this.ReturnComment() without waiting for the POST API to complete.

So GET API fetches the same old data. But as you said if you refresh the page, you will get the new data from API.

So you can do it like this:

  handleComment(e) {
    e.preventDefault();
    var callback = console.log('lol');
    Request.post('http://localhost:3000/api/comments')
      .send({
        idComment: this.state.id,
        author: this.state.name,
        text: this.state.text
      })
      .then(() => this.ReturnComment())
      .end(callback)

    // ... rest of the things
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement