Home > other >  onSubmit React js problems
onSubmit React js problems

Time:02-25

I have a problem with React JS.

I have a form where the user has to pick some options and then write a number, when the user press a button named "Consultar" or press "Enter" (Intro) it suposed to send the form and show a table with the necessary information.

However, when the user press "Enter" the form information is not submitted, the only way is by pressing the button named "Consultar". I have tried using onKeyPress but it did not work.

Could it be some react bug causing the problem and not my code? If it is not something in my code, what I need is that the user can press "Enter" and that it does the same function of the "Consultar" button.

Please help, I am very new in this world of React JS. Here is the code:

const DataForm = ({
  update,
  setIsLoaded,
  setError,
}) => {
  const formatChars = { C: '[1-9]', L: '[0-9]', Z: '[0-9]?' };
  const [tipoCedula, setTipoCedula] = useState('1');
  const [tipoBusqueda, setTipoBusqueda] = useState('1');
  const [numCedula, setNumCedula] = useState('');
  const [emailAddress, setEmailAddress] = useState('');

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm({
    tipoCedula,
    tipoBusqueda,
    numCedula,
    emailAddress,
  });

  const getNumCedulaMask = (pTipoCedula) => {
    if (pTipoCedula === '2') return 'C-LLL-LLLLLL';
    if (pTipoCedula === '3') return 'CLLLLLLLLLLZ';
    if (pTipoCedula === '4') return 'CLLLLLLLLL';

    return 'C-LLLL-LLLL';
  };

  const getRegExFromMask = (pMask, pFormatChars) => {
    let returnValue = pMask;

    Object.keys(pFormatChars).map((item) => {
      if (typeof returnValue.replaceAll === 'function') {
        returnValue = returnValue.replaceAll(item, pFormatChars[item]);
      }
      return returnValue;
    });
    return new RegExp(`^${returnValue}$`);
  };

  const numCedulaMask = getNumCedulaMask(tipoCedula);
  const numCedulaRegEx = getRegExFromMask(numCedulaMask, formatChars);
  const emailRegEx = '^[_a-z0-9-] (.[_a-z0-9-] )*@[a-z0-9-] (.[a-z0-9-] )*(.[a-z]{2,4})$';

  const isValidNumCedula = (inputValue) => {
    const replace = inputValue.replace('_', '');
    if (replace.match(numCedulaRegEx)) {
      return true;
    }
    return 'El formato no es válido';
  };

  const isValidEmail = (inputValue) => {
    if (inputValue.match(emailRegEx)) {
      return true;
    }
    return 'El formato no es válido';
  };
  const onSubmit = async (data) => {
    let searchParameter = '';

    if (data.tipoBusqueda === '1') {
      searchParameter = data.numCedula;
    } else {
      searchParameter = data.emailAddress;
    }
   
    const { ssoBaseUrl } = some restricted information
  
    const apiCall = some restricted information
    
    const requestOptions = {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
    };
    setIsLoaded(true);
    try {
      const result = await fetch(apiCall, requestOptions);
      const datos = await result.json();
      setIsLoaded(false);
      update('reminderResult', datos);
    } catch (e) {
      setError(true);
    }
  };

  return (
    <div>
      <form onSubmit={handleSubmit(onSubmit)} id='formulario' data-testid='formulario-busqueda'>
        <div className='form-group group_TIPO_BUSQUEDA'>
          <label className='label'>Buscar por</label>
          <div>
            <select data-testid="search-type"
              className='form-control select TIPO_BUSQUEDA'
              {...register('tipoBusqueda')}
              defaultValue={tipoBusqueda}
              onChange={(e) => (setTipoBusqueda(e.target.value))}
            >
              <option value='1'>Tipo de cedula</option>
              <option value='2'>Email</option>
            </select></div>
        </div>

        {tipoBusqueda === '1' && <div className='form-group group_TIPO_CEDULA'>
          <label htmlFor='tipoCedula' className='label'>Tipo de cédula</label>
          <div>
            <select data-testid="cedula-tipo-id"
              className='form-control select TIPO_CEDULA'
              {...register('tipoCedula')}
              defaultValue={tipoCedula}
              onChange={(e) => (setTipoCedula(e.target.value))}
            >
              <option value='1'>Cédula Persona Física</option>
              <option value='2'>Cédula Persona Jurídica</option>
              <option value='4'>Número Identificación Tributario Especial (NITE)</option>
              <option value='3'>Documento Identificación Migratorio Extranjeros</option>
            </select>
            {errors.tipoCedula && <p className='error-message'>{errors.tipoCedula.message}</p>}
          </div>
        </div>
        }

        {tipoBusqueda === '1' && <div className='form-group group_NUM_CEDULA'>
          <label htmlFor='numCedula' className='label'>Cédula</label>
          <div>
            <InputMask data-testid="num-cedula"
              className='form-control NUM_CEDULA input'
              {...register('numCedula', {
                required: {
                  value: true,
                  message: 'Este campo es requerido',
                },
                validate: {
                  validValue: isValidNumCedula,
                },
              })}
              formatChars={formatChars}
              onChange={(e) => (setNumCedula(e.target.value))}
              value={numCedula}
              mask={numCedulaMask}
            />
            {errors.numCedula && <p className='error-message' role="alert">Formato cédula incorrecto</p>}
          </div>
        </div>}

        {tipoBusqueda === '2' && <div className='form-group'>
          <label htmlFor='emailAddress' className='label'>Dirección de correo electrónico</label>
          <div>
            <input type="text"
              data-testid="emailAddress"
              className="form-control"
              value={emailAddress}
              {...register('emailAddress', {
                required: 'Este campo es requerido',
                validate: {
                  validValue: isValidEmail,
                },
              })}
              onChange={(e) => (setEmailAddress(e.target.value))}
            />
            {errors.emailAddress && <p className='error-message' role="alert">{errors.emailAddress.message}</p>}
          </div>
        </div>}

        <div className='form-group'>
          <button className='btn-submit float-right' type="submit" data-testid="button-ask">CONSULTAR</button>
        </div>
      </form>
    </div>
  );
};

DataForm.propTypes = {
  update: PropTypes.func.isRequired,
  setIsLoaded: PropTypes.func.isRequired,
  setError: PropTypes.func.isRequired,
};

export default DataForm;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

CodePudding user response:

I did not try your code, but i saw your code and i find here something. You have to write to arrow function in onSubmit.

<form onSubmit={() => handleSubmit(onSubmit)} id='formulario' data-testid='formulario-busqueda'>

If your page getting refresh on submit, then you have to write event.preventDefault() onSubmit.

<form onSubmit={(event) => {
       event.preventDefault();
       handleSubmit(onSubmit);
 } id='formulario' data-testid='formulario-busqueda'>

CodePudding user response:

Here is a code example how to submit forms with enter key:


import React, { useState } from 'react';

export default function App() {
  const [name, setName] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log('form submited');
  };

  return (
    <div>
      <form onSubmit={handleSubmit} >
        <input
          type="text"
          value={name}
          onChange={(e) => setName(e.target.value)}
        />
      </form>
    </div>
  );
}


....

CodePudding user response:

You don't have a handleSubmit function, what you have is an onSubmit function. Therefore, in your onSubmit event listener, you are trying to call a non-existent function

<form onSubmit={handleSubmit(onSubmit)}...

This is how you should call the onSubmit function

<form onSubmit={onSubmit}...
  • Related