Reputation: 363
I have an array of objects that I get from API call like this:
new Promise((resolve) => {
Kit.getSamples(FirstSample, (err, results) => {
if (err) {
return resolve([]);
}
const newData = results.map(item => { return { ...item, name: 'FirstItem' } });
this.setState({
ActivityItem: newData
})
})
My date is added correctly. But then, I need to do another call to API, and add other values to the array, but with a different name.
Kit.getSamples(SecondSample, (err, results) => {
if (err) {
return resolve([]);
}
const newData = results.map(item => { return { ...item, name: 'SecondItem' } });
this.setState({ ActivityItem: [...this.state.ActivityItem, ...[newData]]})
But instead of proper adding to the array, I get an new array inside my array like this:
[{"name": "FirstItem", "quantity": 11, "tracked": false},
{"name": "FirstItem", "quantity": 21, "tracked": true},
[{"distance": 0.310685596118667, "name": "SecondItem", "tracked": false}]]
I wonder if there is a way to add "SecondItem" without having another array inside?
Upvotes: 1
Views: 50
Reputation: 254
You need to replace the following line
this.setState({ ActivityItem: [...this.state.ActivityItem, ...[newData]]})
with this line
this.setState({ ActivityItem: [...this.state.ActivityItem, ...newData]})
Upvotes: 0
Reputation: 282030
newData
is already an array once you obtain it by mapping over results, you don't need to wrap it within []
before using spread syntax while setting state
this.setState({ ActivityItem: [...this.state.ActivityItem, ...newData]})
Upvotes: 1
Reputation: 172
...[newData]
is wrapped in an array, so, the result will be inside an array.
Try removing the brackets, like this: ...newData
Upvotes: 0