React Router Link, onClick Action Not Firing

1.3k views Asked by At

I'm using React Router Dom Link. I'd like to fire an action before I render a new page. The new page's componentDidMount() lifecycle method depends the action firing when a user clicks a username of a post.

code example:

 <Link to={`/Profile/${post.uid}`}
    onClick={(e) => this.handleItemClick(post.uid)}>{post.name}</Link>

handItemClick

handleItemClick = (uid) => {changeUserUidState(uid)}

changeUserUidState is the action creator being dispatched. I am using in line mapStateToProp and mapDispatchToProp like below

export default connect(({posts, userData}) => ({posts, userData}), ({changeUserUidState}))(Feeds);

Action Creator const changeUid = (uid) => {return uid}

export const changeUserUidState = uid => ({
  type: 'UPDATE_UID', payload: changeUid(uid),
});

My payload should only return the uid, which I can simply return rather than invoking changeUid. But, I'm including this code to say that I can console.log() inside of changeUid once the user clicks on a user name, but my redux tools never fire 'UPDATE_UID' and my store never updates the uid.

How can I invoke an action, but the type of action never fires?

my reducer

import initialState from './initialState';

export default function (userUid = initialState.userUid, action) {
  switch (action.type) {
    case 'UPDATE_UID':
      return action.payload;
    default:
      return userUid;
  }
}

and intialState for userUid is an empty string.

1

There are 1 answers

5
DillGromble On

It looks like you're just invoking the function without calling dispatch.

What sends the action to the reducer is to call dispatch. So you'll have to structure what your sending as mapDispatch to props and a function that takes dispatch and returns an object that uses it. Like this:

const mapDispatch = dispatch => ({
  dispatchChangeUID: (uid) => {
    dispatch(changeUserUidState(uid))
  }
})

export default connect(({posts, userData}) => ({posts, userData}), mapDispatch)(Feeds);

Then you'd call props.dispatchChangeUID in the onClick for the link.