Unable to access redux props

Viewed 37

When a user logs in to the app, their information (username, email, etc) is saved in redux. I am able to log in, but my issue is accessing the actual information after logging in.

Here is the code where I am trying to access redux:

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


class LikeComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      likerUID: Firebase.auth().currentUser.uid,
      likerUsername: this.props.user.username, //<------------------ Issue is here

Error:

TypeError: undefined is not an object (evaluating '_this.props.user.username')

How I save the information to redux when a user is authenticated:

dispatch(authUser(Firebase.auth().currentUser.uid, Firebase.auth().currentUser.email, doc.data().username));

Finally my redux actions:

export const authUser = (userid, userEmail, username) => (dispatch) => {
  const data = {
    id: userid,
    username,
    email: userEmail,
  };
  dispatch(setAuthUser(data));
};

In my redux "authUser", I added the line console.log(username); which properly logs the username:

export const authUser = (userid, userEmail, username) => (dispatch) => {
  const data = {
    id: userid,
    username,
    email: userEmail,
  };

  console.log(username);
  dispatch(setAuthUser(data));
};

So the issue is with accessing it, not setting it.

2 Answers

Don't Store Props in State

It is not a good idea to put values from this.props into this.state. Your state will save the very first value of this.props.user.username that it sees. It will not update with new values.

Your constructor function runs and sets the state before the user has logged in so this.props.user is undefined and attempting to access this.props.user.username is an error ("TypeError: undefined is not an object").

Instead, you want to access the username directly from the props when you need to use it. That way you always get the current value from Redux. You can combine with the optional chaining ?. to avoid errors if the user is undefined.

const likerUsername = this.props.user?.username;

Solution was

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