1

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?

3 Answers 3

1

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]})
Sign up to request clarification or add additional context in comments.

Comments

0

...[newData] is wrapped in an array, so, the result will be inside an array.

Try removing the brackets, like this: ...newData

Comments

0

You need to replace the following line

this.setState({ ActivityItem: [...this.state.ActivityItem, ...[newData]]})

with this line

this.setState({ ActivityItem: [...this.state.ActivityItem, ...newData]})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.