react-nativereact-native-swiper

Invalid attempt to destructure non-interable instance


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.


Solution

  • 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.