Giorgia Sambrotta Giorgia Sambrotta - 11 months ago 66
Javascript Question

Destructuring and reordering Array with ES6 and React

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.

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download