Tom Bom
Tom Bom

Reputation: 1721

Class component: Cannot read property 'user' of undefined

I have a class component User and I would like to render what is in the state.user. With Redux Dev Tools I can see that user has correct values.

This is what I have so far:

class User extends Component {
    componentDidMount() {
        this.props.getUser('60ab0b564fbb1d334002c777');
    }

    renderUser = (user) => {
        return (
            user !== {} ? <p>{user.name}</p> : 'User not found'
        )
    }

    render() {
        console.log('props', this.props);
        return (
                <div>
                    {this.renderUser(this.props.users.user)}
                </div>

        )
    }
}

const mapStateToProps = state => ({
    user: state.user,
})

export default connect(mapStateToProps, {
    getUser,
})(User);

When I log this.props under render method, it logs:

getUser: ƒ ()
user: undefined

In my store where I combine reducers, I have:

const rootReducer = combineReducers({
    users: userReducer
});

That's why I need to do this.props.users.user to get to the user.
User's initial state is {}

Upvotes: 0

Views: 26

Answers (2)

underscore
underscore

Reputation: 6887

Your initial state should be

User's initial state is {name: ''} not {}. Cause when the component 1st rendering your function need to access the user.name

Also you have typo here

const mapStateToProps = state => ({
    user: state.users,
})

Upvotes: 0

Irfan wani
Irfan wani

Reputation: 5075

I think you did it wrong at mapStateToProps.

Do this there

user: state.users

Then in the render method

this.props.user.user

Upvotes: 1

Related Questions