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

Filth picture Filth · Feb 9, 2017 · Viewed 65.9k times · Source

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>
    )
}

Answer

conor909 picture conor909 · Dec 31, 2019

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 {}.