Search code examples
javascriptreactjses6-promise

ReactJS looping through set


I've been strugling with this error:

Uncaught TypeError: data.map is not a function

Here's my code:

import React from 'react';
import PropTypes from 'prop-types';

const Foo = ( props ) => {
    const data = props.data;

    return (
        <div>
            {
                !data ? null : (
                    data.map((item, index) =>
                      <a>{item.name}</a>)
                )
            }
        </div>
    )
};

export default foo;

What i pass to Foo is a Set<> of these:

public class Bar extends Dto {
    public BigDecimal id;
    public String name;
}

Any ideas of what might be the case here?

EDIT:

import React, { Component } from 'react';

class AnotherFoo extends Component {

  render () {
    const data = this.props;

    return (
      <div>
      <Foo data={data.resultSet} />
      </div>
    );
  }
}

Solution

  • I'm guessing your resultSet is null or undefined at some point. One thing you can do to add some robustness and clarity is to add propTypes and defaultProps to your component

    import React from 'react';
    import PropTypes from 'prop-types';
    
    const Foo = ( props ) => {
        const data = props.data;
    
        return (
            <div>
                 {
                    !data ? null : (
                        data.map((item, index) =>
                          <a>{item.name}</a>)
                    )
                 }
            </div>
        );
    };
    
    Foo.propTypes = {
      data: PropTypes.arrayOf(PropTypes.shape({
        name: PropTypes.string
      })
    };
    
    Foo.defaultProps = {
      data: []
    };
    
    export default Foo;
    

    This will do a couple things. Give you some warnings when data is the wrong type and or if the items in data are the wrong shape (They should be objects with a name property). Also... it will give you an empty array if data is undefined. This should shed some light on your issue.