React JS Error: Invalid attempt to destructure non-iterable instance

ReactjsEcmascript 6Destructuring

Reactjs Problem Overview


I have a sort filter that takes an array to populate the options. Trying to see the option value equal to the text within the array but I get the error within the title:

Invalid attempt to destructure non-iterable instance

I need to pass the text as the value within the option tag so that when the user updates the filter, the correct text displays to the choice the user made.

Here is my code:

function Sorting({by, order, rp}: SortingProps) {
	const opts = [
		['Price (low)', 'price', 'asc'],
		['Price (high)', 'price', 'desc'],
		['Discount (low)', 'discount', 'asc'],
		['Discount (high)', 'discount', 'desc'],
		['Most popular', 'arrival', 'latest'],
		['Most recent', 'arrival', 'latest'],
	];

	const onChange = (i) => {
		const [text, by, order] = opts[i];
		refresh({so: {[by]: order}});
		/* GA TRACKING */
		ga('send', 'event', 'My Shop Sort By', text, 'Used');
	};
    
    return (
        <div className={cn(shop.sorting, rp.sorting.fill && shop.sortingFill)}>
            <Select className={shop.sortingSelect} label="Sort By" onChange={onChange} value={`${by}:${order}`}>
                {opts.map(([text], i) =>
                    <Option key={i} value={text}>{text}</Option>
                )}
            </Select>
        </div>
    )
}

Reactjs Solutions


Solution 1 - Reactjs

I caused this error a few times because whenever I write a useState hook, which I would do often, I'm used to using an array to destructure like so:

const [ state, setState ] = useState();

But my custom hooks usually return an object with properties:

const { data, isLoading } = useMyCustomFetchApiHook();

Sometime I accidentally write [ data, isLoading ] instead of { data, isLoading }, which tiggers this message because you're asking to destructure properties from an array [], when the object you're destructuring from is an object {}.

Solution 2 - Reactjs

If anybody is using useState() hooks, and facing above issue while using context. They can try below solution.

In place of []

const [userInfo, setUserInfo] = useContext(userInfoContext);

Use {}

const {userInfo, setUserInfo} = useContext(userInfoContext); // {} can fix your issue

Solution 3 - Reactjs

I also encountered a similar error and honestly, I did a very silly mistake maybe because of editor autocomplete.

I had to make use of the useState hook but somehow due to autocomplete, I wrote it like this.

  const [state, setState] = useEffect(defaultValue);

instead of :(.

  const [state, setState] = useState(defaultValue);

Hope it will help as an error message, in this case, was not helpful at all until I spent some time debugging this.

Solution 4 - Reactjs

The error Invalid attempt to destructure non-iterable instance occurs because of a logic/coding error. The following javascript is used to illustrate the problem:

[aaa,bbb] = somefunc()

When somefunc() is called it must return an array of at least two items. If it doesn't there is no way to convert the result from somefunc() into values for aaa and bbb. For example, the code:

[aaa,bbb] = { 'some': 'object'}

would produce this error.

So the error is really a Javascript coding error and it is just happening inside React code that handles this situation by printing the error shown. See MDN for destructuring assignment documentation.

As @Mayank Shukla states in his answer, the answer to the OP question is to fix this line of code:

const [text, by, order] = opts[i];

By changing it to this: const [text, by, order] = opts[i.target.value];

With my above description it should be clearer that opts[i] the original code by the OP was not returning an array of at least 3 items so the javascript runtime was not able to set the values of the variables text, by and order. The modified/fixed code does return an array so the variables can be set.

After looking for an answer to this question I realized that the other answers were correct, and I am just summarizing the root cause of the error message.

Solution 5 - Reactjs

I straight up tried to assign it an empty object!

Bad :(

  const [state, setState] = {};

Good :)

  const [state, setState] = useState({});

Solution 6 - Reactjs

You aren't passing an argument along with your onChange, it's a pretty common thing to miss - however a little less obvious with a select/option combination.

It should look something like:

class Sorting extends React.Component {
  
    constructor(props) {
      super(props);
      
      this.opts = [
          ['Price (low)', 'price', 'asc'],
          ['Price (high)', 'price', 'desc'],
          ['Discount (low)', 'discount', 'asc'],
          ['Discount (high)', 'discount', 'desc'],
          ['Most popular', 'arrival', 'latest'],
          ['Most recent', 'arrival', 'latest'],
      ];
      
      this.state = {
        selected: 0, // default value
      }
      
      this.onChange = this.onChange.bind(this);
    }

    onChange(i) {
      const [text, by, order] = opts[i.target.value];
    };
  
    render() {
      return (
          <div>
              <select onChange={this.onChange} value={this.state.selected}>
                  {this.opts.map(([text], i) =>
                      <option key={i} value={i}>{text}</option>
                  )}
              </select>
          </div>
      )
    }
}
ReactDOM.render(<Sorting />, document.getElementById("a"));

Note I stripped out your classes and styles to keep it simple. Also note you were using uppercase Select and Option - unless these are custom in house components, they should be lowercase.

Note2 I also introduced state, because the state of the select needs to be stored somewhere - if you are maintaining the state of the select box outside of this component, you can obviously use a combination of props/callbacks to maintain that value one level higher.

http://codepen.io/cjke/pen/egPKPB?editors=0010

Solution 7 - Reactjs

I encountered this question because I had the same error, but in order to make it work for me, I wrote

const [someRef] = useRef(null);

When it should have been

const someRef = useRef(null); // removed the braces []

Solution 8 - Reactjs

Make sure your useState is a function call not an array type.

useState('') not useState['']

Solution 9 - Reactjs

Problem is with variable i, i will be the event object, use i.target.value to get the value selected by the user, one more thing you used text as the value of the options, instead of that use the index, it will work, try this:

const onChange = (i) => {
        const [text, by, order] = opts[i.target.value];
        refresh({so: {[by]: order}});
        /* GA TRACKING */
        ga('send', 'event', 'My Shop Sort By', text, 'Used');
    };

    return (
        <div className={cn(shop.sorting, rp.sorting.fill && shop.sortingFill)}>
            <select className={shop.sortingSelect} label="Sort By" onChange={onChange} value={`${by}:${order}`}>
                {opts.map(([text], i) =>
                    <option key={i} value={i}>{text}</option>
                )}
            </select>
        </div>
    )

Check this fiddle: https://jsfiddle.net/5pzcr0ef/

Solution 10 - Reactjs

Invalid attempt to destructure non-iterable instance says the instance you are trying to iterate is not iterable. What you should do is checking whether the opt object is iterable and can be accessed in the JSX code.

Solution 11 - Reactjs

This error can also happen if you have an async function that returns an array, but you forget to run it with await. This will result in that error:

const myFunction = async () => {
  return [1, 2]
}
const [num1, num2] = myFunction();

Whereas this will succeed:

const [num1, num2] = await myFunction();

Solution 12 - Reactjs

When using React Context API, this error can occur if you try to use React.useContext() in a component that is not wrapped in the <ContextProvider>

For example, the following code would throw this error:

const App = () => {
   const [state, setState] = React.useContext(MyContext)

   return (
     <ContextProvider>
        <SubComponent />
     </ContextProvider>
   );
}

You can use the line:

const [state, setState] = React.useContext(MyContext)

inside the SubComponent, but not inside the App component. If you want to use it in the App component, place App component inside another component and wrap the App component in <ContextProvider></ContextProvider>.

const App = () => {
   const [state, setState] = React.useContext(MyContext)

   return (
     <div>
        <SubComponent />
     </div>);
}

const Master = () => {
   <ContextProvider>
      <App/>
   </ContextProvider>
}

Solution 13 - Reactjs

In my Case i did this mistake

> const {width,height} = Dimensions("window") to const[width ,height] = Dimensions("window)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFilthView Question on Stackoverflow
Solution 1 - Reactjsconor909View Answer on Stackoverflow
Solution 2 - ReactjsMaheshvirusView Answer on Stackoverflow
Solution 3 - ReactjsDivyanshu RawatView Answer on Stackoverflow
Solution 4 - ReactjsPatSView Answer on Stackoverflow
Solution 5 - Reactjssigmapi13View Answer on Stackoverflow
Solution 6 - ReactjsChrisView Answer on Stackoverflow
Solution 7 - ReactjsJohnView Answer on Stackoverflow
Solution 8 - ReactjsCharles ChiakwaView Answer on Stackoverflow
Solution 9 - ReactjsMayank ShuklaView Answer on Stackoverflow
Solution 10 - ReactjsBumuthu DilshanView Answer on Stackoverflow
Solution 11 - ReactjsRonzeView Answer on Stackoverflow
Solution 12 - ReactjsRohan HussainView Answer on Stackoverflow
Solution 13 - Reactjsparag barsarView Answer on Stackoverflow