I’m not getting the form clean

Asked

Viewed 25 times

-1

I’m having a problem, I can’t clear the form after Submit.

export default function Home() {

  const initialValue = {
    nome: '',
    sobrenome: '',
    email: '',
    endereco: '',
    numero: '',
    cidade: '',
    bairro: '',
    cep: '',
    numCelular: '',
    numTelefone: '',
  }

  const [values, setValues] = useState(initialValue);

  function onChange(evento) {
    const { name, value } = evento.target;
    setValues({ ...values, [name]: value })
  

  }

  function onSubmit(evento) {
    evento.preventDefault();
    /*     fetch('http://127.0.0.1:8000/clientes/')
        .then(function(res){ 
          return res.json()
        }).then(function (resConvertida){
          console.log(resConvertida)
        }) */

    fetch('http://127.0.0.1:8000/clientes/', {
      method: "POST",
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(values)
      
    })
      .then(response => response.json())
      .then((response) => {
        console.log(response.message);        
      })
         
  } 


  return (
    <div>
      <div>
        <Head>
          <title>Restaurante App</title>
          <meta name='description' content='App de Pedidos em Restaurantes' />
          <meta name='author' content='AgnaldoCordeiro' />
          <link rel="icon" href="/favicon.ico" />
        </Head>
      </div>
      <div>
        <Menu />
      </div>
      <div className={styles.container}>
        <Jumbotron fluid className="conteudo">
          <style>{`.conteudo{
          padding-top: 80px;
          padding-bottom: 80px;
          background-color: black;
          color: white;
          margin-bottom: 0rem !important;          
        }`}</style>
          <Container>
            <h1 className="display-3">App Restaurante</h1>
            <div className="mb-2">
              <form className="row g-3" onSubmit={onSubmit}>
                <div className="col-md-4">
                  <label htmlFor="inputNome" className="form-label">Nome</label>
                  <input type="text" className="form-control" id="inputNome" name="nome" onChange={onChange} />
                </div>
                <div className="col-md-4">
                  <label htmlFor="inputSobrenome" className="form-label">Sobrenome</label>
                  <input type="text" className="form-control" id="inputSobrenome" name="sobrenome" onChange={onChange} />
                </div>
                <div className="col-md-4">
                  <label htmlFor="inputCPF" className="form-label" >CPF</label>
                  <input type="text" className="form-control" id="inputCPF" name="cpf" onChange={onChange} />
                </div>
                <div className="col-md-3">
                  <label htmlFor="inputEmail4" className="form-label" >Email</label>
                  <input type="email" className="form-control" id="inputEmail4" name="email" onChange={onChange} />
                </div>
                <div className="col-md-8">
                  <label htmlFor="inputEndereco" className="form-label" >Endereço</label>
                  <input type="text" className="form-control" id="inputEndereco" name="endereco" placeholder="Apartment, studio, or floor" onChange={onChange} />
                </div>
                <div className="col-md-1">
                  <label htmlFor="inputNum" className="form-label" >Numero</label>
                  <input type="text" className="form-control" id="inputNum" name="numero" onChange={onChange} />
                </div>
                <div className="col-md-3">
                  <label htmlFor="inputCidade" className="form-label" >Cidade</label>
                  <input id="text" className="form-control" id="inputCidade" name="cidade" onChange={onChange} />
                </div>
                <div className="col-md-3">
                  <label htmlFor="inputBairro" className="form-label">Bairro</label>
                  <input type="text" className="form-control" id="inputBairro" name="bairro" onChange={onChange} />
                </div>
                <div className="col-2">
                  <label htmlFor="inputCEP" className="form-label">CEP</label>
                  <input type="text" className="form-control" id="inputCEP" name="cep" onChange={onChange} />
                </div>
                <div className="col-2">
                  <label htmlFor="inputCelular" className="form-label">Celular</label>
                  <input type="tel" className="form-control" id="inputnumCelular" placeholder="(DDD)00000-0000" name="numCelular" onChange={onChange} />
                </div>
                <div className="col-2">
                  <label htmlFor="inputTelefone" className="form-label">Telefone</label>
                  <input type="tel" className="form-control" id="inputnumTelefone" placeholder="(DDD)0000-0000" name="numTelefone" onChange={onChange} />
                </div>
                <div className="text-center">
                  <div className="form-check" className="align-content-center">
                    <input className="form-check-input" type="checkbox" value="" id="invalidCheck" required />
                    <label className="form-check-label" for="invalidCheck">
                      Aceite os termos e condições
                    </label>
                    <div className="invalid-feedback">
                      You must agree before submitting.
                    </div>
                  </div>
                  <div className="col-12">
                    <button type="submit" className="btn btn-primary">Cadastrar</button>
                  </div>

                </div>

              </form>
            </div>

          </Container>
          <Container className="text-center">
            <p className="lead">App de restaurante desenvolvido.</p>
            <hr className="my-2" />
            <p>Modo de Desenvolvimento.</p>
          </Container>

        </Jumbotron>
        <Footer />
      </div>

    </div>

1 answer

0


Basically there the problem is that you are just capturing the event of onChange of inputs and storing them in a state, but their inputs are not "synchronized" with that state, so when resetting the inputs do not reflect this change, I recommend you pass the stored state values to the inputs, for example:

 <input type="text" className="form-control" id="inputNome" name="nome" onChange={onChange} value={values.nome} />

Just apply the value tds inputs and dps return the state to the initial value, for example:

setValues(initialValue)

This is one of the ways to reset the form using controlled components, another way would be to use the function reset native to itself form.

When performing a submit you can capture the form instance and invoke the reset function in this way:

evento.target.reset()

With this approach you wouldn’t need to add the prop value in tds its inputs, but it would be interesting to reset its state in the same way.

Complete example of your function onSubmit

 function onSubmit(evento) {
    evento.preventDefault();
    /*     fetch('http://127.0.0.1:8000/clientes/')
        .then(function(res){ 
          return res.json()
        }).then(function (resConvertida){
          console.log(resConvertida)
        }) */

    fetch('http://127.0.0.1:8000/clientes/', {
      method: "POST",
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(values)
      
    })
      .then(response => {
         response.json()
         evento.target.reset() // reseta os dados do formulário
         setValues(initialValue) // volta o estado para o valor inicial
      })
      .then((response) => {
        console.log(response.message);        
      })
         
  } 

References:

Htmlformelement.reset()

React - Forms

Browser other questions tagged

You are not signed in. Login or sign up in order to post.