0

I'm trying to do a simple map in react-native-swiper. So I use this :

const onlyOneObservation = [...new Array(pagesCount + 1)].map(([key, idx], i) => this.renderPage(key, idx, i))

But with this, I've got this error :

Invalid attempt to destructure non-iterable instance

After research, I don't no where is the problem here.

dippas
  • 58,591
  • 15
  • 114
  • 126
Pentagura
  • 551
  • 2
  • 8
  • 25
  • Hey, this was the top google result for a similar error I was just having for the last hour with React Native. I attached the debugger, but couldn't manage to get any actionable info out of it since I'm too much of a JavaScript newbie. I just wanted to say that the error in my case was that I was setting up a state variable without wrapping it in "React.useState()". It's a similar problem to what you were facing (we both accidentally created a malformed value that didn't have an array in the correct place) – Debug Arnaut Apr 05 '21 at 01:25

1 Answers1

1

The ... operator destructures an existing object / array and makes a new one with the same properties and values. for example:

let obj = {
  val1: 'value1',
  val2: 2
}
let obj2 = { ... obj };
console.log(obj2); // will log: { val1: 'value', val2: 2 };

But what you do is this: [...new Array(pagesCount+1)]. There are 2 problems here:

  1. why even destructure? why not just do (new Array(pagesCount+1)).map( /*code */)?

  2. my guess is that it tries to destructure the array before building it, or maybe trying to apply the ... operator to the new keyword, althought im not sure its what actually happens inside. anyway if you really need this destructure (again, can't understand why), im pretty sure [...(new Array(pagesCount+1))] should work, or just take the array declaration out.

Gibor
  • 1,695
  • 6
  • 20
  • @Acam np man. If you wanna read more about spread syntax to use it better, go [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax). Also, if my answer help you please mark it for the community with the green V near the answer, you will also get reputation for following the community standard way :) – Gibor Aug 12 '19 at 09:36