D
D
DeniSidorenko2020-10-26 08:47:04
React
DeniSidorenko, 2020-10-26 08:47:04

React how to clear a given state?

Good afternoon, there is such a state

const [form, setForm] = useState({
    name: "", price: "", rating: "", weight: ""
  })


On input there is such an event
const onChangeHandler = event => {
    setForm({...form, [event.target.name] : event.target.value})
  }


The question is, after a successful form submission, how to make the state for the fields be ""
If it's easier, how to make the fields clear after submitting

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
twolbe, 2020-10-26
@DeniSidorenko

The simplest solution would be to describe onSubmitHandler, in which you will submit the initial (empty) state to the state, which is better to put in a separate constant (I understand that you are aware of it without me). You will need to pull this onSubmitHandler using the onSubmit attribute of your form:

export default function FuncName(){
  const [form, setForm] = useState({
    name: "", price: "", rating: "", weight: ""
  })

  onSubmitHandler() {
    setForm({
     name: "", price: "", rating: "", weight: ""
   })
  }

  render() {
    return (
      <form onSubmit={onSubmitHandler}>
        <...>
      </form>
    );
  }
}
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question