The error is Invalid attempt to spread non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method

Viewed 2778

I want to use this code to store the checkedbox value in workdays and this event is trigger when the check box is onchange enter code here

const Post = (props) => {
  const [workdays, setForma] = React.useState([]);

  const  handlecheck = (event) => {
    let newArray = [...workdays, event.target.value];

    if (workdays.includes(event.target.value)) {
      newArray = newArray.filter(bhim => bhim !== event.target.value);
    }

    setForma({workdays:newArray});
  }
}
1 Answers

I think the issue is with

setForma({workdays:newArray});

It seems you may have mixed up a class-based component's this.setState syntax with that of the functional component's useState react hook syntax.

workdays is an array, but this state update saves an object with key workdays and value of updated array. On the next change you try to spread an object into an array.

let newArray = [...workdays, event.target.value];

foo = {a: 23, b: 42};
bar = [...foo, 'test']; // error!!

Simply update state with the new array value.

setForma(newArray);
Related