200gSoft
200gSoft

Reputation: 197

React Hooks clear inputs after submit

I started playing with Hooks and I have a useState object with multiple inputs. What I'd like to understand is how to clear the input value after submitting the form.

On the sumbit function I setInput({ Input1: "", Input2: "" }); and this actually cleans the object values but not the input values.

Also, not sure why console.log(input); appears more than once.

import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const [input, setInput] = useState({ Input1: "", Input2: "" });
  const [button, setButton] = useState("Button");
  console.log(input);

  const _handleChange = e => {
    setInput({ ...input, [e.target.name]: e.target.value });
  };

  function _handleSubmit(e) {
    e.preventDefault();
    setInput({ Input1: "", Input2: "" });
    setButton("Submitted");
    setTimeout(() => setButton("Button"), 1000);
    console.log("Submitted");
  }

  return (
    <form onSubmit={_handleSubmit}>
      <input
        type={"text"}
        placeholder={"Input1"}
        name={"Input1"}
        onChange={_handleChange}
      />
      <input
        type={"text"}
        placeholder={"Input2"}
        name={"Input2"}
        onChange={_handleChange}
      />
      <button text="Save" type="submit">
        {button}
      </button>
    </form>
  );
}

Upvotes: 1

Views: 5331

Answers (1)

Dennis Vash
Dennis Vash

Reputation: 53994

Currently, your input is an uncontrolled component, it doesn't aware of the state input.Input1 that handled by _handleChange.

Try adding a value prop to it.

See controlled vs uncontrolled component.

<input value={input.Input1} onChange={_handleChange} />

Edit mystifying-liskov-vmpx8


Moreover, the log appears twice on _handleSubmit because you changing the state twice:

  1. Batched set state - causes a single render and first log.
setInput({ Input1: '', Input2: '' });
setButton('Submitted');
  1. You set a timeout which changes the state after 1000ms - causes a single render and second log.
setTimeout(() => setButton('Button'), 1000);

Upvotes: 2

Related Questions