I am looking for some help in delaying the display of some calculated data until the state that it relies on is set in a parent component. In the below-simplified example, App
has a value set to 0, then some calculations are run and the state is updated.
The problem is that when Calculate
is clicked, the calculation which updates the state of the initial val
hasn't yet happened, and the final value derived from calcOverUnderPayment
is therefore incorrect.
It only displays the correct value on all subsequent clicks.
What could I do to fix this?
Thanks so much in advance.
function App() {
const [val, setVal] = useState(0)
const calculate = () => {
// code to run some calculations which I then set as state
setVal(100)
}
return (
<>
<button onClick={() => calculate()}>Calculate</button>
<Outcome
val={val}
/>
</>
)
}
function Outcome(val) {
const calcOverUnderPayment = (value: number, type: string) => {
if (type === 'under') {
return (value > 0) ? value : 0
} else {
return (value < 0) ? value : 0
}
}
return (
<>
Final Val is {calcOverUnderPayment(val)}
</>
)
}