0

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?

2 Answers 2

3

Use bracket notation :

handleCheckboxChange(value, isChecked, subGroup) {
  // ..
  newApiData = {...prevState.apiData, [subGroup]: [...prevState.apiData[subGroup], value]}
Sign up to request clarification or add additional context in comments.

Comments

1

To make it a bit prettier, you can use this:

handleCheckboxColorChange(value, isChecked, subGroup) {
  this.setState((prevState) => {
      const newState = { ...prevState }
      newState[subGroup] = isChecked ? [ ...newState[subGroup], value ] : newState[subGroup].filter(item => item !== value)
      return newState
  }, () => this.props.handleApiCall(this.state.apiData))
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.