imalik8088 imalik8088 - 1 month ago 8
React JSX Question

React redux Cannot read property 'firstName' of undefined

I'm getting data from the backend (Node) and not able to display a nested object, I've tried to use map but even there I got the same issue/error message.

here is my code or better to same the component.

import React, {Component} from 'react';
import cookie from 'react-cookie';
import {connect} from 'react-redux';
import {fetchUser} from '../../../actions/index';

import UserInfo from './user-info';

class ViewProfile extends Component {

constructor(props) {
super(props);
}

componentWillMount() {
if (cookie.load('user')) {
const userId = cookie.load('user')._id;
this.props.fetchUser(userId);
}
}


render() {
let test = this.props.user.profile.firstName;
return (
<div>
<h1>{this.props.user.email}</h1>
{test}
</div>

);
}
}

function mapStateToProps(state) {
return {
user: state.user.profile
}
}

export default connect(mapStateToProps, {fetchUser})(ViewProfile);


Here's the error



bundle.js:6 Uncaught TypeError: Cannot read property 'firstName' of undefined(…)


I'm getting a object back from the server, it has a the following structure:

{_id: ...,
email: ...,
profile:{firstName: 'a', lastName:'b'},....
}


I want to display the name. How Can I do archive that?

UPDATE 1



I'm sending via the reducer the following:

....
case FETCH_USER:
return {...state, profile: action.payload};

Answer

if fetchUser() is an async function then this.props.user will be undefined inside render() while the user is being fetched. You can add this at the beginning of render()

if(!this.props.user) { // or !this.props.user.profile depending on your initialState
   return null; 
}