Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

148
Visualizações
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 Respostas
Responde à pergunta

0

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

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda