Reputation: 113
I'm currently working on a project which involves logged in users. In my redux state I have a user which is an object that isn't null. But when I try to get a role from this user object I suddenly get an error "state is null"
this.props.userState.user
returns an user object which has a role attribute.
this.props.userState.user.role
throws an error "TypeError: this.props.userState.user is null"
edit: the following is all the code in the entire file.
class ResultsMain extends Component {
componentDidMount() {
firebase.auth().onAuthStateChanged(user => {
if (user)
getUser(user.email).then(foundUser => {
console.log('User found:', foundUser);
this.props.doSetUser(foundUser);
}).catch((err) => {
console.log(err)
this.props.history.push('/');
});
});
}
render() {
console.log("THE PROPS", this.props.userState.user)
if (this.props.userState.role === "teacher") return <TeacherSearchPage/>
else return <Results />
//else return <div> </div>
}
}
function mapStateToProps(state) {
return {
userState: state.userState,
}
}
function mapDispatchToProps(dispatch) {
return {
doSetUser: user => dispatch(userActions.setUser(user)),
}
}
export const resultsMainPage = ReactRedux.connect(mapStateToProps, mapDispatchToProps)(ResultsMain);
The reducer:
const initialState = {
user: null,
finished: false,
}
function copyAndUpdateObj(copiedObject, update) {
return Object.assign({}, copiedObject, update);
}
export default function userReducer(state = initialState, action) {
switch (action.type) {
case INSERT_USER:
return {...state, user: action.userInformation};
case SET_USER: {
let changes = {
user: action.user
}
return copyAndUpdateObj(state, changes);
}
default:
return state;
}
}
Upvotes: 0
Views: 5764
Reputation: 78
Your reducer must be something of the sort:
function reducer(state = initialState, action) {...}
Whatever is the value of this.props.userState
comes from your definition of initialState
at the very beginning. Please make sure to define initialState
object in your application.
Double check if you have you defined userState.user
in your initial state.
Upvotes: 1