Handle multiple states and objects at once, especially when you have a set of related input fields that need to be updated

PHOTO EMBED

Wed Sep 06 2023 03:01:26 GMT+0000 (Coordinated Universal Time)

Saved by @kebin20 #react.js

//THIS IS FASTER

const initialUserInput = {
  "current-savings": 10000,
  "yearly-contribution": 1200,
  "expected-return": 7,
  duration: 10
};
 

function inputChangeHandler(input, value) {
    setUserInput((prevInput) => {
      return {
        ...prevInput,
        [input]: +value
      };
    });
  }

//**NOTE: The +value expression is used to convert the value to a number (i.e., a numeric data type). The unary + operator in JavaScript is used for type conversion, and when applied to a non-number value, it attempts to convert it to a numeric value.

//The +value expression is used to ensure that the value stored in the state object (prevInput) is of numeric data type, regardless of the data type of the value being passed into the inputChangeHandler function.




//THIS IS SLOWER

  // const [enteredCurrentSavings, setEnteredCurrentSavings] = useState(0);
  // const [enteredYearlyContributions, setEnteredYearlyContributions] = useState(
  //   0
  // );
  // const [enteredExpectedReturn, setEnteredExpectedReturn] = useState(0);
  // const [enteredDuration, setEnteredDuration] = useState(0);
  // const [userInput, setUserInput] = useState({
  //   "current-savings": "",
  //   "yearly-contribution": "",
  //   "expected-return": "",
  //   duration: ""
  // });

  // function currentSavingsChangeHandler(e) {
  //   setEnteredCurrentSavings(e.target.value);
  // }

  // function yearlyContributionsChangeHandler(e) {
  //   setEnteredYearlyContributions(e.target.value);
  // }
  // function expectedReturnChangeHandler(e) {
  //   setEnteredExpectedReturn(e.target.value);
  // }
  // function enteredDurationChangeHandler(e) {
  //   setEnteredDuration(e.target.value);
  // }

  // function submitHandler(e) {
  //   e.preventDefault();

  //   setUserInput({
  //     "current-savings": enteredCurrentSavings,
  //     "yearly-contribution": enteredYearlyContributions,
  //     "expected-return": enteredExpectedReturn,
  //     duration: enteredDuration
  //   });

  //   calculateHandler(userInput);
  // }
content_copyCOPY