I’ve built a simple interface for selecting items from a menu, contained in a component called Sodas
, and it’s displayed in the Parent component: VendingMachine
.
As it is, Sodas
is able to successfully change the state in the VendingMachine
, however, the state cannot be changed within the VendingMachine
itself.
The following code represents the VendingMachine
component:
import Sodas from './Sodas';
const VendingMachine = () =>
{
// Track selected soda
const [selectedSoda, setSoda] = useState({ sodaName: '', stock: 0 });
const handleSodaSelection = (soda) => setSoda(soda);
// Reset the selected soda
const sellSoda = () => setSoda({ sodaName: '', stock: 0 });
return (
<div>
Soda to Purchase: {selectedSoda.sodaName}
<Sodas handleSodaSelection={handleSodaSelection} />
<div onClick={sellSoda}>Buy Selected Soda</div>
</div
}
The following code represents the Sodas
Component
function Sodas({ handleSodaSelection })
{
// Tracks soda selected, and returns to Parent component
const [sodaSelected, setSodaSelected] = useState({ sodaName: '', stock: 0 });
React.useEffect(() => handleSodaSelection(sodaSelected), [sodaSelected, handleSodaSelection]);
return (
<div className='soda_container'>
<div onClick={() => setSodaSelected({ sodaName: 'Cola', stock: 7 })}>Soda</div>
</div>)
}
Specifically, the issue is that setSoda
does not work within VendingMachine
and only works when passed to the Sodas
component. I’m not sure if this can only work as a one way relationship or if there is something I’m missing in the syntax.
Any help or references to relevant documentation would be greatly appreciated.