The below is a dummy reproduction of a part of an app I am writing.
I am mapping
an array of data using const test
that return days of the week. Once I click on a certain day, and this certain day is not present in this.state.testingDates.array
i use setState
to add this day of the week into this.state.testingDates.array
.
When I click on a certain day I get the following error Invalid attempt to spread non-iterable instance
.
Why can't I spread ...array
, so I preserve the old state
with my state
organized in this way, having array: []
at the same level than classFrequency
?
If I move array
one level up(ending with this.state.array
, it all works smoothly.
Here is my code
import React from "react";
import "./styles.css";
export default class App extends React.Component {
state = {
testingDates: {
array: [],
classFrequency: [
{ day: "Sun", DayOfWeek: 0, toggleClassColor: "inherit" },
{ day: "Mon", DayOfWeek: 1, toggleClassColor: "inherit" },
{ day: "Tue", DayOfWeek: 2, toggleClassColor: "inherit" },
{ day: "Wed", DayOfWeek: 3, toggleClassColor: "inherit" },
{ day: "Thu", DayOfWeek: 4, toggleClassColor: "inherit" },
{ day: "Fri", DayOfWeek: 5, toggleClassColor: "inherit" },
{ day: "Sat", DayOfWeek: 6, toggleClassColor: "inherit" }
]
}
};
nonIterableHandler = (childDay, childIndex) => {
const classFrequency = this.state.testingDates.classFrequency;
if (!this.state.testingDates.array.includes(childDay.day)) {
this.setState(
({ array }) => ({
array: [...array, classFrequency[childIndex].day]
}),
() => {
console.log("array spreads...", this.state.array);
}
);
}
};
render() {
let test = this.state.testingDates.classFrequency.map((val, index) => (
<p
key={val.day}
style={{ cursor: "pointer" }}
onClick={() => this.nonIterableHandler(val, index)}
>
{val.day}
</p>
));
return (
<div className="App">
<h1>testing non-iterable</h1>
{test}
</div>
);
}
}