I have an object to collect data to send to an API:
apiData: {
colors: [],
years: [],
// ..
}
Many of the children of this apiData are arrays like colors and years, I call these 'subgroups'. A user can select a multitude of subgroups with checkboxes that trigger:
handleCheckboxColorChange(value, isChecked) {
let newApiData = '';
this.setState( (prevState) => {
if (isChecked === true) {
newApiData = {...prevState.apiData, colors: [...prevState.apiData.colors, value]}
} else {
newApiData = {...prevState.apiData, colors: [...prevState.apiData.colors.filter(item => item !== value)]
}
}
return {apiData: newApiData}
}, () => this.props.handleApiCall(this.state.apiData))
}
I use a similar function for the other 'subgroups'. For years, all that changes in the function is colors to years. So I wish to create a more general function that can take a 'subgroup' as argument to target the right array in my object. I tried to pass a third variable (a string) subGroup like so:
handleCheckboxChange(value, isChecked, subGroup) {
// ..
newApiData = {...prevState.apiData, subGroup: [...prevState.apiData.subGroup, value]}
This does not work (I guess because it is now looking for the child 'subgroup' in my object). How can I make this work?