React Redux - mapDispatchToProps called for every event in a map function

168 views Asked by At

Within my component I have a 'OnClick' handler that is supposed to fire a function called 'onSelectProject' within mapDispatchToProps that dispatches actions to the store. In this case it passes the id of the project passed from the click event

The problem I am having is that onSelectProject is firing for every project on a single click. If I have 10 projects the console.log within the function will show 10 times, one for every project.

index.js (ProjectComponent)

export function ProjectComponent({
  selectedProject,
  projects,
  onSelectProject,
  onGetProjects,
}) {
  useInjectReducer({ key, reducer });
  useInjectSaga({ key, saga });

  useEffect(() => {
    onGetProjects();
  }, []);

  return (

    { projects.map((project, index) => {
       return <ul key={project.id} className="project">
                  <li>{project.name}</li>
                  <li>{project.createdAt}</li>
                  <li><a onClick={onSelectProject(project.id)} href="#" title="Preview this Project"><img src={view_icon} alt="view through icon"/></a></li>
              </ul>
    })}

);
}
const mapStateToProps = createStructuredSelector({
  projects: makeSelectProjects(),
  selectedProject: makeSelectProject()
});

export function mapDispatchToProps(dispatch) {
  return {
    onSelectProject: (id) => {
      console.log(id); 
      dispatch(selectProject(id));
    }
    onGetProjects: () => {
      dispatch(getProjects());
    }
  };
}

const withConnect = connect(
  mapStateToProps,
  mapDispatchToProps,
);

export default compose(
withConnect, 
)(ProjectComponent);

Why is onSelectProject being fired for every project on a single click?

I can provide more code if necessary or requested.

1

There are 1 answers

0
Clio Orgyán On BEST ANSWER

make sure to pass function references not actual calls so your function is not called on every render but when you actually click the button:

onClick={() => onSelectProject(project.id)}