Take data from an editing form - React

Asked

Viewed 1,041 times

-1

I’m developing a single page where I can edit a user’s data, but I had problems developing with Formik, I didn’t have much choice, since it is better in many ways. So I tried to use it and I was able to load the user data in the input of the editing form, however, the data I try to change is not updated, because it is not taking the input data (both the data that is loaded into the input, and the data that I input)so I was wondering what’s wrong with my form and the logic I’m using.

Note: I have tried the API put method I am consuming and working.

import React, {useState, useEffect} from 'react';
import {Form, FormGroup, Label, Input, Container, CustomInput, Button } from 'reactstrap';
import { Link, useParams } from "react-router-dom";
import { useHistory} from 'react-router-dom';
import '../../assets/css/main.css'
import './style.css'
import { useFormik } from "formik";
import * as Yup from "yup";
import api from '../../services/api'


const FormEditar = (props) => {
  const {id} = useParams('');
  const obj = {id: '', nome: '', telefone: '', dtNascimento: '', cpf: '', cnpj: '', categoria: '' };
  const {nome, telefone, dtNascimento, cpf, cnh, categoria} = props.data;
  const initialValues = props.data.id === undefined ? obj : {id, nome, telefone, dtNascimento, cpf, cnh, categoria};
  const enableReinitialize = true;

const history = useHistory();
const formik = useFormik({
  initialValues,
  enableReinitialize
});

const DisplayErrors = (props) => {
  const { msgError } = props
  return(
      <>
      {msgError && <span className="validate-error">{msgError}</span>}
      </>    
  )
}

const [sendNome, setNome] = useState('');
const [sendTelefone, setTelefone] = useState('');
const [sendDtNascimento, setDtNascimento] = useState('');
const [sendCpf, setCpf] = useState('');
const [sendCnh, setCnh] = useState('');
const [sendCategoria, setCategoria] = useState([]);
const [motorista, setMotorista] = useState('');

const handleChange = (event) => {
  setNome({ ...sendNome, [event.target.name]: event.target.value })
  setTelefone({ ...sendTelefone, [event.target.name]: event.target.value })
  setDtNascimento({ ...sendDtNascimento, [event.target.name]: event.target.value })
  setCpf({ ...sendCpf, [event.target.name]: event.target.value })
  setCnh({ ...sendCnh, [event.target.name]: event.target.value })
  setCategoria({ ...sendCategoria, [event.target.name]: event.target.value })
}

function onSubmit(e) {
  e.preventDefault()
  let errors = formik.errors;
  let values = formik.values;

  if (Object.keys(errors).length > 0 || values.email === "" ) {
    alert("Os dados devem ser preenchidos corretamente!");
    return;
  }


    api.put(`motoristas/${id}`, initialValues)
    .then(() => {
        alert(`Dados atualizados com sucesso!`)
        history.push('/');
    }).catch((error) =>  alert("Não foi possível atualizar os dados, tente novamente!"))
}
return (
  <Container id="form-input">
    <h2>Edite seus dados</h2>
    <div id="box-input" >
      <Form method="put" onSubmit={onSubmit}>
          <FormGroup >
            <Label for="nome">Nome:</Label>
            <Input type="text" name="nome" id="nome" placeholder="Nome Completo" 
            for="nome"
            {...formik.getFieldProps("nome")}
            /> {formik.errors && <DisplayErrors msgError={formik.errors.nome}/>}
          </FormGroup>
          <FormGroup>
            <Label for="dtNascimento">Data de Nascimento:</Label>
            <Input type="date" name="dtNascimento" id="dtNascimento" placeholder="00/00/0000" 
            onChange={formik.handleChange} {...formik.getFieldProps("dtNascimento")}
            /> {formik.errors && <DisplayErrors msgError={formik.errors.dtNascimento}/>}
          </FormGroup>
          <FormGroup>
            <Label for="telefone">Telefone:</Label>
            <Input type="text" name="telefone" id="telefone" placeholder="Telefone com DDD" onChange={formik.handleChange} {...formik.getFieldProps("telefone")}
            /> {formik.errors && <DisplayErrors msgError={formik.errors.telefone}/>}
          </FormGroup>
          <FormGroup>
            <Label for="cpf">CPF:</Label>
            <Input type="text" name="cpf" id="cpf" placeholder="CPF" 
            onChange={formik.handleChange} {...formik.getFieldProps("cpf")}
            /> {formik.errors && <DisplayErrors msgError={formik.errors.cpf}/>}
          </FormGroup>
          <FormGroup>
            <Label for="cnh">CNH:</Label>
            <Input type="text" name="numero" id="numero" placeholder="Número da CNH..."  onChange={formik.handleChange} {...formik.getFieldProps("cnh")}
            /> {formik.errors && <DisplayErrors msgError={formik.errors.cnh}/>}
          </FormGroup>
          <FormGroup>
            <Label for="categoria" className="categoria">Marque a(as) categoria(as) da sua CNH: </Label>
              <CustomInput type="checkbox" id="exampleCustomCheckbox"  label="A" inline  onChange={formik.handleChange} {...formik.getFieldProps("categoria")}
              /> {formik.errors && <DisplayErrors msgError={formik.errors.categoria}/>}
              <CustomInput type="checkbox" id="exampleCustomCheckbox2" label="B" inline onChange={formik.handleChange} {...formik.getFieldProps("categoria")}
              /> {formik.errors && <DisplayErrors msgError={formik.errors.categoria}/>}
              <CustomInput type="checkbox" id="exampleCustomCheckbox3" label="C"  inline onChange={formik.handleChange} {...formik.getFieldProps("categoria")}
              /> {formik.errors && <DisplayErrors msgError={formik.errors.categoria}/>}
              <CustomInput type="checkbox" id="exampleCustomCheckbox4" label="D" inline onChange={formik.handleChange} {...formik.getFieldProps("categoria")}
              /> {formik.errors && <DisplayErrors msgError={formik.errors.categoria}/>}
              <CustomInput type="checkbox" id="exampleCustomCheckbox5" label="E" inline onChange={formik.handleChange} {...formik.getFieldProps("categoria")}
              /> {formik.errors && <DisplayErrors msgError={formik.errors.categoria}/>}
              <CustomInput type="checkbox" id="exampleCustomCheckbox6" label="AAC" inline onChange={formik.handleChange} {...formik.getFieldProps("categoria")}
              /> {formik.errors && <DisplayErrors msgError={formik.errors.categoria}/>}
          </FormGroup>
          <Button type="submit" className="btn-form-voltar" to="/" tag={Link}>Voltar</Button>
          <Button type="submit" className="btn-form-salvar">Salvar</Button>
          </Form>
    </div>
  </Container>   
  );

};

export default FormEditar;

Meu formulário de edição i

1 answer

1


From what I saw from your example, the API receives the data from "initialValues", but the data that would be updated would be in the state. I see a problem with the state update, since you save all the state variables with the same value.

I have an example that updates the state, but does not use Hooks, this is an example of a registration form. I think it will serve as an example for you to adjust your code.

import React, { Component } from "react";
import PropTypes from "prop-types";

import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import { Creators as EnderecoActions } from "../../store/ducks/endereco";

class Endereco extends Component {
  static propTypes = {
    enderecoAdicionarRequest: PropTypes.func.isRequired
  };
  state = {
    tipo: "",
    endereco_novo: "",
    numero: "",
    complemento: "",
    bairro: "",
    cidade: "",
    estado: "",
    cep: "",
  };
  componentDidMount(){
    document.title = "Endereço";
    const { enderecoTipoRequest } = this.props;
    enderecoTipoRequest();
  }
  salvar = e => {
    e.preventDefault();

    const {  tipo, endereco_novo, numero, complemento, bairro, cidade, estado, cep} = this.state;
    const { enderecoAdicionarRequest} = this.props;
    let continuar = true;
    let mensagem = "";

    if (tipo === "" || endereco_novo === "" || numero === "" || bairro === "" || cidade === "" || estado === "" || cep === ""){
      alert("Por favor preencha todos os dados do endereço");
      continuar = false;
    } 
    if (continuar) {
      const dados = {
        codigo_usuario: localStorage.getItem("@SISTEMA:usuario"),
        tipo: tipo,
        rua: rua,
        numero: numero,
        compl: complemento,
        bairro: bairro,
        cidade: cidade,
        estado: estado,
        cep: cep,
      }
      enderecoAdicionarRequest(dados);
      this.props.fechar();
    } else {
      alert(mensagem);
    }
  };

  alterar = e => {
    this.setState({ [e.target.name]: e.target.value });
  };

  
  render() {
    const { endereco } = this.props;
    const cep = this.props.endereco.cep;
    return (
      <section id="content">
        <div className="container clearfix">
          <h3>Adicionar Endereço</h3>
          <form onSubmit={this.salvar}>
            <div className="form-row">
              <div className="form-group col-md-6">
                <label>Tipo de Endereco</label>
                <select name="tipo" id="tipo" className="form-control"  onChange={this.alterar}>
                  <option value="">Selecione...</option>
                  {endereco.tipo.map(item => (
                    <option key={item.codigo} value={item.codigo}>{item.titulo}</option>
                    ))}
                </select>
              </div>
              <div className="form-group col-md-6">
                <label>CEP</label>
                <input
                  type="text"
                  className="form-control"
                  id="cep"
                  placeholder={"00000000"}
                  name="cep"
                  onChange={this.alterar}
                />
              </div>
            </div>
            <div className="form-row">
              <div className="form-group col-md-6">
                <label>Endereço</label>
                <input
                  type="text"
                  className="form-control"
                  id="endereco_novo"
                  placeholder="Rua X"
                  name="endereco_novo"
                  onChange={this.alterar}
                />
              </div>
              <div className="form-group col-md-6">
                <label>Número</label>
                <input
                  type="text"
                  className="form-control"
                  id="numero"
                  placeholder={"00"}
                  name="numero"
                  onChange={this.alterar}
                />
              </div>
            </div>
            <div className="form-row">
              <div className="form-group col-md-6">
                <label>Complemento</label>
                <input
                  type="text"
                  className="form-control"
                  id="complemento"
                  placeholder="Apto, casa"
                  name="complemento"
                  onChange={this.alterar}
                />
              </div>
              <div className="form-group col-md-6">
                <label>Bairro</label>
                <input
                  type="text"
                  className="form-control"
                  id="bairro"
                  placeholder="Bairro Y"
                  name="bairro"
                  onChange={this.alterar}
                />
              </div>
            </div>
            <div className="form-row">
              <div className="form-group col-md-6">
                <label>Cidade</label>
                <input
                  type="text"
                  className="form-control"
                  id="cidade"
                  placeholder="Apto, casa"
                  name="cidade"
                  onChange={this.alterar}
                />
              </div>
              <div className="form-group col-md-6">
                <label>Estado</label>
                <input
                  type="text"
                  className="form-control"
                  id="estado"
                  placeholder="Sigla"
                  name="estado"
                  onChange={this.alterar}
                />
              </div>
            </div>
            <br />
            <button type="submit" className="btn btn-primary">
              Salvar
            </button>
          </form>
        </div>
      </section>
    );
  }
}

const mapStateToProps = state => ({
  endereco: state.endereco
});

const mapDispatchToProps = dispatch =>
  bindActionCreators(EnderecoActions, dispatch);

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Endereco);

Since it only updates the session if the field is changed, in case of editing an existing record, you could save the current data in the state when creating the component.

Browser other questions tagged

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