'TypeError: Invalid attempt to spread non-iterable instance. In set an Array into state in class component
I'm using React Navigation to get an array called additional using this.props.route.params when I navigate to a page, and when I render the screen I want to set the state details in the class component with the array additional, I'm still new to JavaScript and this is what I came up with:
Array
Array [
Object {
"data": Array [
Object {
"id": 1.01,
"price": 1,
"selected": false,
"title": "Ranch",
"type": "Sides",
},
Object {
"id": 1.02,
"price": 1,
"selected": false,
"title": "Blue Cheese",
"type": "Sides",
},
],
"required": false,
"type": "Sides",
},
Object {
"data": Array [
Object {
"id": 2.01,
"price": 1,
"selected": false,
"title": "Hot Sauce",
"type": "Sauces",
},
Object {
"id": 2.02,
"price": 1,
"selected": false,
"title": "Medium Sauce",
"type": "Sauces",
},
],
"required": true,
"type": "Sauces",
},
]
Screen
class DisplayItem extends Component {
constructor(props) {
super(props);
this.state = {
sides: [],
details: [],
}
}
render() {
const { additional } = this.props.route.params;
const { sides, details } = this.state;
if (additional !== undefined) {
sides.forEach((item) => {
item['selected'] = false
});
additional.forEach((a, i) => {
a["data"] = sides.filter(b => b.type == a.type);
});
this.setState((details) => {return [...details, additional]})
}
I've attempted to use ()=>this.setState({details: additional}) but it returns only an empty array, then I've tried the above method and it returns the error: TypeError: Invalid attempt to spread non-iterable instance.
Solution 1:[1]
You are trying to spread an array ...details, which is not possible.
Can you put debugger or console.log before this.setState((details) => {return [...details, additional]}) and can you tell us what is in additional?
Btw in ()=>this.setState({details: additional}) you are trying to set additional which you probably assume is array, but it probably is just a string value.
Solution 2:[2]
You are trying to spread the whole state which is an object not the array part of it
Here you can destruct the details part from the current state before spreading it like this:
this.setState(({details}) => {return [...details, additional]})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Michal Šajdík |
| Solution 2 | Mustafa Magdy |
