1

I want to clear the input field after upload and submit the form.

I have checked couple of documentation, where its said after submitting the form I can return the initial state.

Here is my code

 state = {
    firstname: "",
    lastname: "",
    email: "",
    file: null
  };

  onDrop = e => {
    this.setState({ file: e.target.files[0] });
    console.log({ file: e.target.files[0] });
  };

  handleChange = e => {
    this.setState({ [e.target.id]: e.target.value });
  };
  handleSubmit = async e => {
    e.preventDefault();
    console.log(this.state);
    const formData = new FormData();
    formData.append("file", this.state.file);
    formData.append("upload_preset", process.env.REACT_APP_UPLOAD_PRESET);

    const response = await axios.post(
      `https://api.cloudinary.com/v1_1/${process.env.REACT_APP_CLOUD_NAME}/image/upload`,
      formData
    );

    await this.props.addPerson({
      variables: {
        firstname: this.state.firstname,
        lastname: this.state.lastname,
        email: this.state.email,
        image: response.data.url
      },
      refetchQueries: [{ query: getperson }]
    });

    this.setState({ firstname: " ", lastname: "", email: " ", file: null }); **this is where i retutn the initial state after submitting the form, but it did not work**
  };

This is my form setup

  <React.Fragment>
        <div>
          <form id="addPerson" onSubmit={this.handleSubmit}>
            <div className="field">
              <label> Firstname </label>
              <input type="text" id="firstname" onChange={this.handleChange} />
            </div>
            <div className="field">
              <label> Lastname </label>
              <input type="text" id="lastname" onChange={this.handleChange} />
            </div>
            <div className="field">
              <label> Email </label>
              <input type="email" id="email" onChange={this.handleChange} />
            </div>
            <input type="file" onChange={this.onDrop} />
            <button>Add Person</button>
          </form>
        </div>
      </React.Fragment>
2
  • You haven't set the value with state for example - email, firstname and lastname. reactjs.org/docs/forms.html Commented Jan 2, 2020 at 14:23
  • Please check the answer and accept it, if it work for you. Commented Jan 2, 2020 at 14:24

2 Answers 2

1

It doesn't work because your inputs are not fully controlled by react, If you want to control these inputs, you need to specify the value attribute like this :

<input type="text" id="firstname" value={this.state.firstname} onChange={this.handleChange}/>
<input type="text" id="lastname" value={this.state.lastname} onChange={this.handleChange}/>

Note that the file input is always uncontrolled in react (see the documentation), so you need to reset it manually by using a reference :

 constructor() {
   this.fileRef = React.createRef();
   ...
 }

 handleSubmit = async e => {

   // Reset the file input
   this.fileRef.current.value = '';
 };

 render() {
   ...
   <input type="file" ref={this.fileRef} onChange={this.onDrop} />
   ...
 }
Sign up to request clarification or add additional context in comments.

Comments

0

You haven't set the value attribute in html input with state value.

Since the value attribute is set on our form element, the displayed value will always be this.state.value, making the React state the source of truth.

Since handleChange runs on every keystroke to update the React state, the displayed value will update as the user types.

With a controlled component, every state mutation will have an associated handler function. This makes it straightforward to modify or validate user input.

For more details please check here.

Use following code,

    <React.Fragment>
        <div>
        <form id="addPerson" onSubmit={this.handleSubmit}>
            <div className="field">
            <label> Firstname </label>
            <input type="text" id="firstname" value={this.state.firstname} onChange={this.handleChange} />
            </div>
            <div className="field">
            <label> Lastname </label>
            <input type="text" id="lastname" value={this.state.lastname} onChange={this.handleChange} />
            </div>
            <div className="field">
            <label> Email </label>
            <input type="email" id="email" value={this.state.email} onChange={this.handleChange} />
            </div>
            <input type="file" onChange={this.onDrop} />
            <button>Add Person</button>
        </form>
        </div>
    </React.Fragment>

Hope this will help you !!!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.