Reputation: 1641
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);
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?
I'm sending via the reducer the following:
....
case FETCH_USER:
return {...state, profile: action.payload};
renderUserInfo() {
if (this.props.user.profile) {
return (
<UserInfo profile={this.props.user.profile}/>
)
}
}
render() {
return (
<div>
<h1>{this.props.user.email}</h1>
{this.renderUserInfo()}
</div>
);
}
Upvotes: 0
Views: 1586
Reputation: 223
It looks like you're dealing with async operation. You can dispatch an action of type FETCH_USER when you're don with fetching the data. But it's always better to multiple action type to describe what fetching state you're in. Here is an example of how to deal with async operation.
Upvotes: 1
Reputation: 3556
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;
}
Upvotes: 3