I have an object model pattern as below
this.state = {
data: {
audi: {
engine: '2.5',
gearbox: 'auto',
fuel: 'petrol'
},
bmw: {
engine: '3.0',
gearbox: 'auto',
fuel: 'petrol'
},
merc: {
engine: '6.3',
gearbox: 'manual',
fuel: 'petrol'
}
}
}
My goal is to:
- Loop through the data and render
- Map value changes in the HTML to the corresponding keys in the this.state.data object
I haven't used an Array, as it has to look like above object pattern when posting it.
At the moment here is how I am trying to do this:
//To render
Object.entries(this.state.data).map((x,index) =>
<p>x.key</p> //Trying to reach 'audi' with x.key
// Render each KPV in object
{x.key}: <input key={index} onChange={this.handleChange} value={x.value}/>
)
Then to update the corresponding values in the same state model:
// To update the state model with changed values
setData = (key, val) => {
this.setState(state => ({
data: {
...state.data,
obj: { [key]: val },
//Don't know how to map to state properly!
}
}));
};
// Handle input change
handleChange = key => e => {
this.setData(key, e.target.value);
};
Please could anyone advise me on this approach, many thanks :)