0

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>
  )
}
R.M. Reza
  • 725
  • 1
  • 8
  • 20
  • What's wrong with what you have? It's simple, clear, doesn't create a lot of unnecessary intermediate objects, make a lot of unnecessary function calls, ... – T.J. Crowder Oct 22 '21 at 09:40
  • @T.J.Crowder I feel this is too wordy. I want to get the same behavior when I initialize state with an empty object, the problem with this React is giving me a warning. – R.M. Reza Oct 22 '21 at 09:43
  • Okay. The linked question's answers give you various alternatives, particularly [this one](https://stackoverflow.com/a/38340730/157247). – T.J. Crowder Oct 22 '21 at 09:47
  • Nothing different from the solution I wrote in `submitHandler`, I want to get another way, unfortunately my question is considered a duplicate, even though I already explained that I want to use another way, which should not be a duplicate. – R.M. Reza Oct 22 '21 at 09:53
  • What do you mean "nothing different from the solution I wrote"?? The first example in the answer I linked above is `let o = Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null));`. That's utterly and completely different from what you have in the question. (In your case, you'd change `v != null` to just `v` if you want it to match your test above.) Your question is considered a duplicate because it **is** a duplicate by SO's rules for duplicates, please see the [help] for details. – T.J. Crowder Oct 22 '21 at 09:56
  • 1
    "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?". Thank you i really appreciate your answer. I don't seem to be able to convey my meaning properly because of my language limitations. – R.M. Reza Oct 22 '21 at 10:01
  • So you want to avoid having "empty" values in `user` itself so you can send that directly, rather than creating a new object without them in `submitHandler`? (The confusion may be your use of "delete." Creating a new object without empty properties isn't *deleting* empty properties, it's just avoiding adding them.) – T.J. Crowder Oct 22 '21 at 10:04
  • (Unrelated question: Shouldn't there be `value` properties on your `input` elements that use `user`'s property values?) – T.J. Crowder Oct 22 '21 at 10:06
  • "Unrelated question": Yes I forgot not to write that in the example. There doesn't seem to be any other solution as I want, for the time being I'll be using the one I've created. Thanks for your answer, I got another way to remove empty property. – R.M. Reza Oct 22 '21 at 10:13
  • Okay, no worries. Just in case you did want to avoid having blank values in `user` in the first place, you could do it [like this](https://pastebin.com/NgiqWwqk). But I would probably just remove them (or create a new object without them) in `submitHandler` instead (as you do above). Happy coding! – T.J. Crowder Oct 22 '21 at 10:15

2 Answers2

0
Object.keys(user).forEach((item) => !user[item] && delete user[item);
Ram Rana
  • 194
  • 6
  • That modifies the original object, which you must not do when objects stored in React state. Also, the OP said *"I can of course delete the empty properties manually in submitHandler..." which is exactly what this does. They're looking for a *different* solution. – T.J. Crowder Oct 22 '21 at 09:37
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

Andrew F
  • 504
  • 2
  • 7
  • Please vote to close as duplicate when the answers to a different question answer a question, rather than posting an answer. More in the [help]. – T.J. Crowder Oct 22 '21 at 09:39