how to delete a property from an object if the key’s value is false in React?

  forms, javascript, object, reactjs, use-state

I have a form component. When I submit the form, it returns the following object

{
  email: "[email protected]"
  fieldName1: {fieldVal: "advance", isCheck: false}
  fieldName2: {fieldVal: "alerts", isCheck: true}
  first_name: "Yoda"
  last_name: "S"
  organization: "dog's"
}

fieldName1 and fieldName2 are checkbox values. All the others are input text values. I want to have the filedName property whose isCheck is false to be removed/deleted from the object, so that it won’t appear when user submits the form. I tried the following in the handleIsCheckClick function, but it deleted everything in the object.

setUserDetails((prev) => {
  if(target.type="checkbox" && !prev[name].isCheck) {
    const { name, ...newUserDetails} = prev;
    return newUserDetails
  }
})

The follow is the completed component

    export default function SignUpFormContainer() {
  const [userDetails, setUserDetails] = useState({});

    const handleUserDetailsChange = ({ target }) => {
        const { name, value } = target;
    
        setUserDetails((prev) => ({
          ...prev,
          [name]: value,
        }));
      };

  const handleIsCheckClick = ({ target }) => {
    const { name, value, checked } = target;

    setUserDetails((prev) => ({
      ...prev,
      [name]: {
        fieldVal: value,
        isCheck: checked,
      }
    }));

    target.checked
      ? target.classList.add("checked")
      : target.classList.remove("checked");
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    alert(JSON.stringify(userDetails, "", 2));
  };

  const clearUserDetails = () => {
    setUserDetails({});
  };

  return (
    <div className="form-container">
      <SignUpForm
        onSubmit={handleSubmit}
        userDetails={userDetails}
        handleIsChecked={handleIsCheckClick}
        handleUserDetailsChange={handleUserDetailsChange}
        clearUserDetails={clearUserDetails}
      />
    </div>
  );
}

Source: Ask Javascript Questions

LEAVE A COMMENT