Home > OS >  Trying to add to React State Array using spread or push, Error: TypeError: array is not iterable
Trying to add to React State Array using spread or push, Error: TypeError: array is not iterable

Time:01-19

I've created an array in the initial state object and I'm trying to add items to the array whenever a checkbox is checked and remove the item whenever it's unchecked.

The function I'm using is pretty simple and I don't see any reason why it shouldn't work. I'm using setState to spread the items in the array and add the new item on the end, but I keep getting a TypeError on the browser saying that the array is not iterable. I've tried using typeof to see if it's an array and it results in undefined.

Click here to see the error I receive

My code is:

class Step3 extends React.Component {
    constructor() {
        super()

        this.state = {
            missingList: [],
        }

    }

    handleChangeArray = e => {
        this.setState({
            missingList: [...this.state.missingList, e.target.name]
        })
        console.log(this.state.missingList)
    }

    render() {

        const { currentProductType, ProductSubtype } = this.props

        return (
            <div className="row mt-4">

                <h4 className='subtitle'>Missing List</h4>

                {
                    systemData[`${currentProductType}`][`${ProductSubtype}`].parts.map((item, _id) =>
                        <CustomCheckbox
                            col={3}
                            key={_id}
                            name={item}
                            text={item}
                            onChange={this.handleChangeArray}
                        />
                    )

                }
            </div>
        )
    }
}

The systemData points to a nested object where the list comes from and uses the map method to render the checkbox

CodePudding user response:

Well it is because the handleChange is not bound to the Step3 class. So, when CustomCheckBox invokes the handleChange, the context of this would be referring to CustomCheckBox and not Step3. So, this.missingList is correctly undefined. It's simply the scope of this.

Check this minimal reproducer of your use case. Commenting the bind line will result in the error you have posted. https://codesandbox.io/embed/upbeat-smoke-q0iei?fontsize=14&hidenavigation=1&theme=dark

Further reading: https://reactjs.org/docs/handling-events.html

  •  Tags:  
  • Related