3

I wanted to use a destructuring solution to reorder my array within my React container which it should be pretty straight forward. Given an array a1 = ['hello', 'hi', 'hola']

componentDidMount() {
  const { a1 } = this.props
  this.a2 = []
  [a2[2], a2[0], a2[1]] = a1  --> this line give an error!!
  console.log('new ordered array', a2) // ['hola', 'hello', 'hi'] --> this print properly my new array
}

If I try to console log or use it in render I got undefined The error I got at that line is:

Uncaught (in promise) TypeError: Cannot set property '#<Object>' of undefined

I really don't get it why I can print the value correctly in the console.log but when I try to actually use it in the code it doesn't work. It's maybe something React cycle related? I also tried to use it within my state but got the same error.

3
  • Have a look at the line with the error, you have a dot (.) where a comma should be Commented Aug 17, 2017 at 10:25
  • It's called destructuring, not desconstructing. Commented Aug 17, 2017 at 10:26
  • thanks @PeterMader Commented Aug 17, 2017 at 10:38

2 Answers 2

5

This line gives you an error because this is one of those rare cases when automatic semicolon insertion lets you down. Never start new line with ( or [], otherwise interpreter considers it as continuation of the previous line and treats [ or ( as property access operation or function invocation.

This will work:

this.a2 = [];
[a2[2], a2[0], a2[1]] = a1

Or this:

this.a2 = []
;[a2[2], a2[0], a2[1]] = a1
Sign up to request clarification or add additional context in comments.

1 Comment

that's exactly what it was happening! Problem is" my lint won't allow me to add semicolon -.- frontend development, so much fun :) I anyway already solved in another way but at least now i know, Thanks!
1

There is an . instead of , in this line [a2[2], a2[0]. a2[1]] = a1 --> this line give an error!!

1 Comment

You are right but i just mistype the question here, in my actual code, there is a comma

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.