J.Zh
J.Zh

Reputation: 1

React add array to state array

I am new to React. In my state, I am trying to have an empty array initialized to store polygons.

The structure I want to have is an array like this.state.polyList = [[dot1,dot2,dot3...],[dot1,dot2,dot3...]]

I am trying to have a

let newState = Object.assign({},this.state);
let newValue = [points]; // "points" is [dot1,dot2,dot3...]
console.log(newValue[0][0]); // able to print correctly
newState.polyList = newState.polyList.concat(newValue)
this.setState(newState)

However, when I later log the state.polyList, I only have a few empty array ([]) inside list

Upvotes: 0

Views: 100

Answers (4)

TOLULOPE ADETULA
TOLULOPE ADETULA

Reputation: 788

Best way to do this would be is structuring.

let oldState = [1,2,4]

this.setState ([...oldState, [new state array]])

Upvotes: 0

Muhammad Zeeshan
Muhammad Zeeshan

Reputation: 4748

Deep cloning in react doesn't work the way you are doing. A way that i prefer to use is by spread operator. You can do something like:

let newState = [...this.state.polyList];
newState.push(points)
this.setState({ polyList: newState });

Hope this works for you.

Upvotes: 0

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11001

Change to something like below.

let newValue = [points]; // "points" is [dot1,dot2,dot3...]
console.log(newValue[0][0]); // able to print correctly

let newState = { ...this.state, 
                 polyList: [...this.state.polyList, newValue] };

this.setState(newState)

Upvotes: 0

akhtarvahid
akhtarvahid

Reputation: 9769

You can add like this array to state array

 state = {
    items: [4,5,6],
  };

function to add

  handleClick = e => {
  this.setState({
   items:[...this.state.items,[Math.floor(Math.random()*100),7,8]]
   })
  };

Upvotes: 1

Related Questions