Ray Coder
Ray Coder

Reputation: 1111

I want to push / add object to the state react native (invalid attempt to spread non iterable instance)

i want to add object to my state and i have search to solve it but all of it doesn't work

this.state = {
   value : {name:'test'}
};

i want to add an object {coordinate:'0,0'} in this.state.value

I tried this one but i got error : invalid attempt to spread non iterable instance

let floors = [...this.state.value];
floors.push({ coordinate: '0,0'});
this.setState({ value:floors });

I tried this one but i got error : invalid attempt to spread non iterable instance

this.setState({
   value:[...this.state.value, {coordinate: '0,0'}]
});

I tried this one but i got error : _this2.state.value.concat is not a function

this.setState( {
   value: this.state.value.concat({koordinat:coor})
});

please help me to solve it

Upvotes: 1

Views: 194

Answers (1)

Dave Newton
Dave Newton

Reputation: 160191

You tried to spread a map into an array.

If you want to start with an array, then change your initial state:

this.state = { value: [{ name: 'test' }] }

Then you can use your original code, either of the first two examples.

Your second example fails for the same reason.

The third example doesn't make sense, you're trying to concat onto an object.


Based on the comments none of the original code really addressed what you are trying to do, namely, simply adding a property to an existing object. As schogges points out, this is trivial:

this.setState({
  value: { ...this.state.value, coordinate: '0, 0') }
})

This spreads an existing object into a new object with an additional property.

That said: coordinates aren't strings, they're objects.

Upvotes: 5

Related Questions