Meteor React Error: Cannot read property '0' of undefined

1k views Asked by At

On a very simple Meteor app using React, there is a table that list out all the registered users from the Meteor.users collection.

However when trying to display the email address of each user, the browser JS console is throwing the following error, although the email address is correctly rendered on the HTML page.

Exception from Tracker recompute function:
TypeError: Cannot read property '0' of undefined
    at Users.render (User.jsx:8)

Why is this error happening?

/imports/ui/User.jsx

import React, { Component } from 'react';

export default class Users extends Component {
    render() {
        return (
            <tr>
                <td>{ this.props.user._id}</td>
                <td>{ this.props.user.emails[0].address }</td>  // this is line 8
            </tr>
        )
    }
}

/imports/ui/App.jsx

import React, { Component, PropTypes } from 'react';
import { createContainer } from 'meteor/react-meteor-data';

import User from './User';

export class App extends Component {

    renderUsers() {
        return this.props.users.map((user) => (
            <User key={user._id} user={user} />
        ));
    }


    render() {
        return (
            <div>
                <h1>Users</h1>

                <table>
                    <tbody>
                        <tr>
                            <td>ID</td>
                            <td>Email</td>
                        </tr>
                        { this.renderUsers() }
                    </tbody>
                </table>
            </div>
        )
    }
}

App.propTypes = {
    users: PropTypes.array.isRequired
}

export default createContainer(() => {
    return {
        users: Meteor.users.find().fetch()
    }
}, App);
1

There are 1 answers

8
John Ruddell On BEST ANSWER

Well it would seem this.props.user.emails is undefined. are you sure this is the correct key you are looking for?

ways to fix this.

pull in a library like lodash (it will change your life)

import _ from 'lodash';
....
<td>{_.get(this.props, 'users.emails[0].address', 'UNKNOWN ADDRESS')}</td>

if you dont want to pull in something like lodash then check to see if the value is there..

var address = 'UNKNOWN ADDRESS';
if(this.props.users.emails && this.props.users.emails.length > 0) {
     address = this.props.users.emails[0].address;
}