How to Clean Formalario in React

Asked

Viewed 33 times

0

So guys I’m having a problem, I made a formalario that sends input data by Submit to an API, but I can’t file the data 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>`insira o código aqui`
  • fetch(url)&#xA; .then((response) => {&#xA; if (response.status >= 200 && response.status <= 299) {&#xA; return response.json();&#xA; } else {&#xA; throw Error(response.statusText);&#xA; }&#xA; })&#xA; .then((jsonResponse) => {&#xA; // do whatever you want with the JSON response&#xA; }).catch((error) => {&#xA; // Handle the error&#xA; console.log(error);&#xA; });

  • https://learnwithparam.com/blog/how-to-handle-fetch-errors/

1 answer

-1

Use setValues within the function onSubmit:

function onSubmit(evento) {
  evento.preventDefault();
  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))
    .then((response) => {
        // Limpe o formulário definindo todos os campos como vazios
        setValues({
          nome: '',
          sobrenome: '',
          email: '',
          endereco: '',
          numero: '',
          cidade: '',
          bairro: '',
          cep: '',
          numCelular: '',
          numTelefone: '',
        }));
    }
}
  • i did it but it didn’t work yet not erase the form only from a bad request when sending again

  • The answer should solve @Myag, with an addendum, setValues could simply be setValues(initialValue). The error may be in your jsx. If you want, you can add it to the question and I can parse.

  • I put all the code on the page

Browser other questions tagged

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