Call function only after multiple states have completed updating
So, there are some issues with your implementations:
- Using non-state variables to update the state in your useEffect:
Explanation:
In displayConversionTo
when you run the loop to push elements in convertToUnitsArray
, and then set the state dialogStage
to convertTo
, you should be facing the issue that the updated values are not being rendered, as the change in state triggers a re-render and the convertToUnitsArray is reset to an empty array because of the line:
let convertToUnitsArray = [];
thus when your useEffect
runs that is supposed to update the
dialogUnits
to convertToUnitsArray
, it should actually set the dialogueUnits to an empty array, thus in any case the updated units should not be visible on click of the initial units list.
useEffect(() => {
if (dialogStage == "convertTo") {
// as your convertToUnitsArray is an empty array
// your dialogue units should be set to an empty array.
setDialogUnits(convertToUnitsArray)
}
}, [dalogStage]);
- You are trying to store an array of react components in the state which is not advisable: http://web.archive.org/web/20150419023006/http://facebook.github.io/react/docs/interactivity-and-dynamic-uis.html#what-components-should-have-state
Also, refer https://stackoverflow.com/a/53976730/10844020
Solution: What you can do is try to save your data in a state, and then render the components using that state, I have created a code sandbox example how this should look for your application. I have also made some changes for this example to work correctly.