display multiply calculations from input data

  javascript, reactjs, use-state

I’m busy with one project with REACT and faced a problem. I have user input data. I use it in some math formulas and need to display all results in one table. The problem is, that result2 relies on the result1, result3 relies on the result2 etc.

 input data:
 const [volume, setVolume] = useState(0);
 const [price, setPrice] = useState(0);
 const [fixedCosts, setFixedCosts] = useState(0);

results:

 const [revenue, setRevenue] = useState(volume * price);
 const [netProfit, setNetProfit] = useState(revenue - fixedCosts);

functions:

function handleFormSubmit(event) {
  event.preventDefault();

  function handleRevenueChange() {
   setRevenue(volume * price);     // both values are from input
  }
  function handleNetProfitChange() {
   setNetProfit(Math.round(revenue - fixedCosts));  // revenue here is result of the first calculations
  }
 }

I retrieve data, I can use it and display. This part works. My problem: with the first submit, I calculate "revenue" in the first formula, so I change its state, but in the mean time its current state is 0. So the second formula gives nothing. When I press submit the second time, bcz "revenue" is already updated, I can use it and it calculates the second formula. So If I have there five functions, I need to press five times on submit, bcz every value state updates one by one (they rely on each other).

  1. How can I calculate everything at first and then only display all data with one button submit.
  2. Even better- how can I make data to be calculated and displayed automatically if there is any input without pressing button at all? (thinking about onBlur, but don’t know how to use it, and stil issue to calculate everything first)

Thank you for any help.

Source: Ask Javascript Questions

LEAVE A COMMENT