devYuraKim / react

udemy - jonas schmedtmann
0 stars 0 forks source link

c01-tip-calculator/src/App_OnMyOwn.js #1

Closed devYuraKim closed 3 months ago

devYuraKim commented 3 months ago
export default function App() {
  const [bill, setBill] = useState(0);
  const [totalTip, setTotalTip] = useState(0);

  function handleChange(e) {
    setBill(e.target.value);
  }

  return (
    <div>
      <Bill bill={bill} onChange={handleChange} />
      <Tip setTotalTip={setTotalTip} />
      <div>{bill + bill * totalTip}</div>
      <button>reset</button>
    </div>
  );
}

function Tip({ setTotalTip }) {
  const [tip1, setTip1] = useState(0);
  const [tip2, setTip2] = useState(0);

  function handleChange1(e) {
    setTip1(Number(e.target.value));
    setTotalTip(Math.round((tip1 + tip2) / 2));
  }

  function handleChange2(e) {
    setTip2(Number(e.target.value));
    setTotalTip(Math.round((tip1 + tip2) / 2));
  }

  return (
    <>
      <TipSeparate onChange={handleChange1}>
        How did you like the service?
      </TipSeparate>
      <TipSeparate onChange={handleChange2}>
        How did your friend like the service?
      </TipSeparate>
    </>
  );
}

States for tip1, tip2 are updated without any problem but totalTip won't change. Can't figure out what's missing between App and Tip component.

devYuraKim commented 3 months ago

My code was lagging in state updates. Additionally, the values (0.05, 0.1 and 0.2) were too small and were just being displayed as 0. With larger numbers, the states were being updated even with my original code(but of course there was still the lag problem, so the calculation wasn't correct).

  function handleChange1(e) {
    const newTip1 = Number(e.target.value);
    setTip1(newTip1);
    setTotalTip((newTip1 + tip2) / 2);
  }

  function handleChange2(e) {
    const newTip2 = Number(e.target.value);
    setTip2(newTip2);
    setTotalTip((newTip2 + tip1) / 2);
  }
function TipSeparate({ onChange, children }) {
  return (
    <div>
      {children}
      <select onChange={onChange}>
        <option value={0}>0%</option>
        <option value={5}>5%</option>
        <option value={10}>10%</option>
        <option value={20}>20%</option>
      </select>
    </div>
  );
}