-1

I'm new to react, have created a chat using reactjs. I'm using "POST" request through fetch to post new message for a particular conversation. My Objective is when i send a message, then it should clear the input but unable to clear the input after sending message. Anyone can help me in this?

"How to post message through API successfully?"

Chandan
  • 25
  • 8

3 Answers3

0

You'd need to read value in your Input from the state, and then reset the state after sending the request:

handleChange = event => {
    this.setState({ [event.target.name]: event.target.value });
  };

  handleSend = event => {
    const { phonNo } = this.props.phonNo;
    event.preventDefault();
    console.log("phone : " + "+" + phonNo);
    this.setState({ toPhoneno: phonNo });
    console.log("phonefkjdk : " + "+" + this.state.toPhoneno);
    const data = {
      toPhoneNumber: "+" + this.state.toPhoneno,
      body: this.state.body
    };
    fetch("/api/messages", {
      method: "POST",
      body: JSON.stringify(data),
      headers: { "Content-Type": "application/json" }
    })
      .then(res => res.json())
      .then(() => {
        this.setState({body: ''}); // reset input value
      });
  };

  render () {
    return (
      <div>
        <input
          className="sendMessage"
          onChange={this.handleChange}
          id="body"
          name="body"
          value={this.state.body || ''} //read value from the state
        />
        <Button onClick={this.handleSend} className="sendBtn" icon>
          <Icon name="send" color="blue" />
        </Button>
      </div>
    );
  }
Clarity
  • 10,730
  • 2
  • 25
  • 35
0

Here instead of using the controlled inputs, you can use the uncontrolled inputs also as there is no need to re-render the component on each value entered.

Controlled vs Uncontrolled Inputs

Following the above link, once you are done sending the message, you can easily clear the input as

this.input.value = ''

Controlled inputs are mostly used when you need to update the state immediately when u type. I feel you might not need it here.

Vishal Sharma
  • 316
  • 1
  • 8
-1

You can use simple Javascript for this.
After your API response, type this where you want the input box to be cleared.

document.getElementById('myInput').value = '';

UPDATE:

Use ReactDOM to change the value as follows:

<input type="text" ref="input" />
ReactDOM.findDOMNode(this.refs.input).value = '';
PiNaKa30
  • 608
  • 7
  • 20