Here I am passing state up via props through an intermediary component. The intermediate component has a handler (onIntermediatePropsHandler) has some logic (const formatedAmount = enteredAmount += 10;) that executes on the data being passed. It would seem that the logic only executes once. Why is this?
const Parent = () => {
const onParentPropsHandler = amount => {
console.log(amount)
}
return (
<div>
<Intermediate IntermediateToParent={onParentPropsHandler} />
</div>
)
}
const Intermediate = (props) => {
const onIntermediatePropsHandler = enteredAmount => {
const formatedAmount = enteredAmount += 10;
props.IntermediateToParent(formatedAmount)
}
return (
<div>
<Child ChildToIntermediate={onIntermediatePropsHandler} />
</div>
)
}
export const Child = (props) => {
const [index, setIndex] = useState(null)
const onClickHandler = (index) => {
setIndex(index + 1);
props.ChildToIntermediate(index);
}
return (
<div>
<button onClick={() => onResetState(index)}>Reset Counter</button>
</div>
)
}
This gives the console log of
I am not sure what you are trying to do. But if you want to format the updated index, you should call the parents function in the useEffect
function, because index is set asynchronously, so you are getting the old state. So your child state will look like this:
useEffect(() => {
props.ChildToIntermediate(index); // Updated index value
});
const onClickHandler = (index) => {
setIndex(index + 1);
}
This way, after updating your index, you will call the parent function, according to the updated index (and not anymore with the old state)