Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

147
Vistas
How To Delete an Empty State Input Value Before Sending in React

How to clear empty form input state in React before sending to server?

For example, in the form below, if user.name is not filled in then the object sent to the server is:

{ age: "19" }

Note: I can of course delete the empty properties manually in submitHandler, but is there any other way that doesn't require me to manually delete?

const UserAdd = () => {
  const [user, setUser] = useState({
    name: "",
    age: ""
  });

  const inputChangeHandler = (e) => {
    setUser({ ...user, [e.target.name]: e.target.value })
  }

  const submitHandler = (e) => {
    e.preventDefault();
    
    // Start Solution
    const userWithoutEmptyProperties = {};
    for(const key in user) {
      if(user[key]) {
        userWithoutEmptyProperties[key] = user[key];
      }
    }
    // End Solution

    // send "userWithoutEmptyProperties" to server 
  }

  return (
    <form onSubmit={submitHandler} >
      <input type="text" name="name" onChange={inputChangeHandler} />
      <input type="text" name="age" onChange={inputChangeHandler} />
      <button type="submit">Add</button>
    </form>
  )
}
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Object.keys(user).forEach((item) => !user[item] && delete user[item);
about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use one-liner:

let o = Object.fromEntries(Object.entries(obj).filter(([_, v]) => v));

More about this: Remove blank attributes from an Object in Javascript

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda