3

I'm trying to clear the form data once creating a form submission with Axios. The message goes through fine and the response is logged to the page, but the data in each text field remains on the page after submission.

I tried adding a resetForm function where I set the form back to it's original blank state, but that isn't working.

import React, { Component } from 'react';
import { Grid, Cell, Textfield, Button } from 'react-mdl';
import './Contact.css';
import axios from "axios";

class Contact extends Component {
    constructor(props){
        super(props);
        this.state = {fullName: "", email: "", message: ""};
    }  

    resetForm = () => {
        this.baseState = this.state
        this.setState(this.baseState)
    }

    handleForm = e => {
        axios.post(
        "https://formcarry.com/s/axiosID", 
        this.state, 
        {headers: {"Accept": "application/json"}}
        )
        .then(function (response) {
            let successMessage = document.querySelector('.success-message');
            successMessage.innerHTML = JSON.stringify(response.data.title);
        })
        .catch(function (error) {
            let successMessage = document.querySelector('.success-message');
            successMessage.innerHTML = JSON.stringify(error);
        });

        e.preventDefault();
    }
    handleFields = e => this.setState({ [e.target.name]: 'e.target.value' });

        render() {
            return (
                    <Grid>
                        <Cell col={6}>
                            <h2>Contact Me</h2>
                            <hr/>
                            <div style={{ width: '100%' }} className="contact-list">
                                <form onSubmit={this.handleForm}>
                                    <Cell col={12}>
                                        <Textfield type="text" id="fullName" name="fullName" className="full-name"
                                        onChange={this.handleFields}
                                        label="Full name"
                                        floatingLabel
                                        style={{width: '200px'}}
                                        />
                                    </Cell>
                                    <Cell col={12}>
                                    {/* Textfield with floating label */}
                                        <Textfield type="email" id="email" name="email" className="email-address"
                                        onChange={this.handleFields}
                                        label="Email address"
                                        floatingLabel
                                        style={{width: '200px'}}
                                        />
                                    </Cell>
                                    <Cell col={12}>
                                        {/* Floating Multiline Textfield */}
                                        <Textfield name="message" id="message" className="text-body"
                                        onChange={this.handleFields}
                                        label="Your message..."
                                        rows={10}
                                        style={{width: '400px'}}
                                        />
                                    </Cell>
                                    <Button raised accent ripple type="submit" onClick={this.resetForm}>Send</Button>
                                    <div className="success-message">
                                        <label></label>
                                    </div>
                                </form>
                            </div>
                        </Cell>
                    </Grid>
            )
        }
    }


export default Contact;

All I really want is for the text fields fullName, email and message to clear once I submit the form but the data remains on the page.

JackJack
  • 181
  • 1
  • 1
  • 20

5 Answers5

4

You do not need the resetForm function (get rid of it altogether), just set your state in the handleForm like so:

UPDATE: You also need to add the value prop to each input to make it a controlled input see below:

import React, { Component } from 'react';
import { Grid, Cell, Textfield, Button } from 'react-mdl';
import './Contact.css';
import axios from "axios";

class Contact extends Component {
  constructor(props) {
    super(props);
    this.state = { fullName: "", email: "", message: "" };
  }

  handleForm = e => {
    axios.post(
      "https://formcarry.com/s/axiosID",
      this.state,
      { headers: { "Accept": "application/json" } }
    )
      .then(function (response) {
        let successMessage = document.querySelector('.success-message');
        successMessage.innerHTML = JSON.stringify(response.data.title);
      })
      .catch(function (error) {
        let successMessage = document.querySelector('.success-message');
        successMessage.innerHTML = JSON.stringify(error);
      });

    e.preventDefault();
    this.setState({fullName: '', email: '', message: ''}) // <= here
  }
  handleFields = e => this.setState({ [e.target.name]: e.target.value }); 

  render() {
    return (
      <Grid>
        <Cell col={6}>
          <h2>Contact Me</h2>
          <hr />
          <div style={{ width: '100%' }} className="contact-list">
            <form onSubmit={this.handleForm}>
              <Cell col={12}>
                <Textfield type="text" id="fullName" name="fullName" className="full-name"
                  onChange={this.handleFields}
                  value={this.state.fullName} // <= here
                  label="Full name"
                  floatingLabel
                  style={{ width: '200px' }}
                />
              </Cell>
              <Cell col={12}>
                {/* Textfield with floating label */}
                <Textfield type="email" id="email" name="email" className="email-address"
                  onChange={this.handleFields}
                  value={this.state.email} // <= here
                  label="Email address"
                  floatingLabel
                  style={{ width: '200px' }}
                />
              </Cell>
              <Cell col={12}>
                {/* Floating Multiline Textfield */}
                <Textfield name="message" id="message" className="text-body"
                  onChange={this.handleFields}
                  value={this.state.message} // <= here
                  label="Your message..."
                  rows={10}
                  style={{ width: '400px' }}
                />
              </Cell>
              <Button raised accent ripple type="submit">Send</Button>
              <div className="success-message">
                <label></label>
              </div>
            </form>
          </div>
        </Cell>
      </Grid>
    )
  }
}


export default Contact;

As a side note: look into React refs for grabbing dom elements... read more here: https://reactjs.org/docs/refs-and-the-dom.html

SakoBu
  • 3,972
  • 1
  • 16
  • 33
  • Thanks SakoBu. Same issue. It's not throwing any errors but even after trying your method it still doesn't clear. – JackJack Jan 18 '19 at 17:23
  • @Ang - oh, that's also becuase it's not a controlled input... I'll update my answer... – SakoBu Jan 18 '19 at 17:27
  • I tried your updated code but whenever I type into any of the text boxes, it reads `e.target.value` and I cannot change the values. – JackJack Jan 18 '19 at 17:54
  • @Ang... In your `handleFields` get rid of the quotes from 'e.target.value' , instead of the actual value you are getting the string – SakoBu Jan 18 '19 at 17:55
2

You need to clear the state after submission. After calling setState the react render will be called again with empty values that we set, Hope this helps

 .then(function (response) {
        let successMessage = document.querySelector('.success-message');
         // here clear the state,
         this.setState({
           fullName: '',
           email: '',
           message: '',
         });
        successMessage.innerHTML = JSON.stringify(response.data.title);
    })
Aashish Karki
  • 356
  • 2
  • 7
1

You could do something like

 resetForm = () => {
    this.setState({fullName: "", email: "", message: ""});
}

That would reset those values back to nothing.

remoo
  • 177
  • 1
  • 1
  • 10
1

Your state gets updated when you change the form input.

handleFields = e => this.setState({ [e.target.name]: 'e.target.value' });

State is not a static object.

You'll have to manually update the field values.

resetForm = () => {
    this.setState({fullName: "", email: "", message: ""})
}
Rishabh
  • 1,205
  • 1
  • 11
  • 20
0

From showed code it is not visible if values of form fields had been assigned by values from state. (e.g. for fullName field: value = this.state.fullName). If value had not been assigned the form would not have been re-rendered, even though the setState had been properly defined.

gehbiszumeis
  • 3,525
  • 4
  • 24
  • 41
ahmed.zubaca
  • 107
  • 2
  • 7