devio
devio

Reputation: 1169

React/Redux: TypeError: Cannot read property 'target' of undefined

I'm trying to update my state (list of users) with the edited fields of a certain user (firstName, lastName, email). The idea is whenever the user changes the value of an input in the form, a creator action is triggered to update the user object in the state with the new values. Below is my pieces of code:

In my reducers.js:

case actionCreators.changeUserValues.getType():
return {
...state,
usersList: [
  ...state.usersList.map((user) => {
    if (user.username === action.payload.username) {
      return {
        ...user,
        [action.payload.name]: action.payload.value,
      };
    }
    return user;
  }),
],
editButtonDisabled: false,
submitButtonDisabled: true,
selectedUserProfile: {
  userObject: {
    ...state.selectedUserProfile.userObject,
    [action.payload.name]: action.payload.value,
  },
},
};

In the actionCreators.js file:

const changeUserValues = createAction(CHANGE_USER_VALUES, userData => userData);

const onValueChange = event => (dispatch, getState) => {
  const { value, name } = event.target;
  const { username } = getState().selectedUserProfile.username;
  return dispatch(changeUserValues({ name, value, username }));
};

In my Containter:

const mapDispatchToProps = dispatch => ({
  // some stuff
  onValueChange: () => dispatch(actionCreators.onValueChange()),
});

To test my code, I edit the form and I get this error TypeError: Cannot read property 'target' of undefined in the onValueChange() actionCreator code. I don't know how to pasS/capture the event (as I'm trying to 'redux' this)

Upvotes: 1

Views: 388

Answers (1)

ageoff
ageoff

Reputation: 2828

You are not passing in the event to your reducer

const mapDispatchToProps = dispatch => ({
  // some stuff
  onValueChange: (event) => dispatch(actionCreators.onValueChange(event)),
});

For a more complete answer... when you are using the input value just pass the event. As long as the mapDispatchToProps has the value in there as well it should make it all the way to your action/reducer.

<input onChange={e=>this.props.onValueChange(e)} />

Upvotes: 2

Related Questions