Home > Enterprise >  How to destructure objects from Redux store?
How to destructure objects from Redux store?

Time:10-19

The following code works when implemented with only React, but I get

Uncaught TypeError: _ref is not iterable

specifically on destructuring [id, name] when I start using Redux:

class GridView extends React.Component {

    render() {
        return (
            <div>
                {this.props.itemList.map(([id, name]) =>
                    <Item
                        key={id}
                        name={name}
                        id={id}
                    />)}
            </div>
        )
    }
}

export default connect((state) => ({itemList: state.itemList}), actions)(GridView);

It works if I write it like this instead:

class GridView extends React.Component {

    render() {
        return (
            <div>
                {this.props.itemList.map(el =>
                    <Item
                        key={el.id}
                        name={el.name}
                        id={el.id}
                    />)}
            </div>
        )
    }
}

export default connect((state) => ({itemList: state.itemList}), actions)(GridView);

I don't understand what it means by _ref. Is there a way to properly destructure data retrieved from the Redux store?

CodePudding user response:

Your error has nothing to do with Redux. You need to use curly braces ({}) when destructuring an object, not square brackets ([]), which would be to destructure an array.

{this.props.itemList.map(({ id, name }) => (
  <Item
    key={id}
    name={name}
    id={id}
  />
))}
  • Related