Where exactly should I deal with the problem of this component not loading with the desired state
?
My render method causes the following error...
Uncaught TypeError: Cannot read property 'email' of undefined
...even though the JSON.stringify
line shows me that the email property does (eventually) exist.
The console.log
down in mapStateToProps
confirms that state loads first without the any user
property (thus causing the error).
Behold my naive attempt to resolve this in my constructor method. It's not working.
What is the right way to deal with this situation? Some conditional inside the render method? Tried that too but still no luck.
import React, {Component, PropTypes} from 'react';
import {connect} from 'react-redux';
import * as actions from '../actions';
class Feature extends Component {
constructor(props){
super(props);
this.state = {
'auth': {
'user':{
email:'',
id:''
}
}
}
}
componentWillMount() {
this.props.fetchMessage(); // puts the user object into state
}
render() {
return (
<div className="feature">
Here is your feature
{JSON.stringify(this.props.user , null, 2)}
{this.props.user.email}
</div>
);
}
}
function mapStateToProps(state) {
console.log('state',state);
return { user: state.auth.user }
}
export default connect(mapStateToProps, actions)(Feature);
/////////// action /////////
export function fetchMessage(){
return function(dispatch){
axios
.get(ROOT_URL, {
headers: {
authorization: localStorage.getItem('token')
}
})
.then((response) => {
dispatch({
type: FETCH_MESSAGE,
payload: response.data.user
})
})
}
}
///////////////// reducer /////////////
var authReducer = (state={}, action) => {
console.log('action.payload',action.payload);
switch(action.type){
case AUTH_USER: return {...state, error: '', authenticated: true};
case UNAUTH_USER: return {...state, error: '', authenticated: false};
case AUTH_ERROR: return {...state, error: action.payload};
case FETCH_MESSAGE: return {...state, user: {
email: action.payload.email,
id: action.payload._id
}};
default: return state;
};
};