Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

146
Views
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 answers
Answer question

0

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

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!