0

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

1
  • Since your state is nested, you need to do a deep clone to properly copy your state to prevent state mutation. Object.assign() doesn't do a deep clone. Commented Jan 22, 2020 at 5:36

4 Answers 4

1

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

Comments

0

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)

Comments

0

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.

2 Comments

Since an array is a reference type he is assigning the value even after he does concatenation newState.polyList = newState.polyList.concat(newValue) so that may not be the exact reason. Deep Clone might be as mentioned in the comments by jayce.
@Ramesh Yes, you are right. I will update my answer. Thanks.
0

Best way to do this would be is structuring.

let oldState = [1,2,4]

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

1 Comment

thanks for noting. But it is still not working. The list turns to be all filled with empty arrays.

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.