Bomber
Bomber

Reputation: 10957

Action creator, too many params being sent to reducer

I am sending to much to my reducer:

export const setStudent = (data, value, year, group, showStudent) => ({
    type: "SET_STUDENT",
    data,
    value,
    year,
    group,
    showStudent
});

In my reducer I send it the data I need to sort, and the relevant params:

  case "SET_STUDENT":
        let studentName = data
            .find(option => {
                return option.id == year;
            })
            .options.find(option => {
                return option.id == group;
            })
            .options.find(option => {
                return option.id == value;
            }).label;

        return { ...state, student: value, label: studentName };

Rather than send data in the action, can I import this in my reducer, like so:

import { data } from "../config/calendars.js";

My mapDispatchToProps is becoming very confusing also:

const mapDispatchToProps = dispatch => ({
    fetchEvents: id => dispatch(fetchEvents(id)),
    isLoadingCredentials: loadingCredentials =>
        dispatch(isLoadingCredentials(loadingCredentials)),
    setCredentials: credentials => dispatch(setCredentials(credentials)),
    setYear: year => dispatch(setYear(year)),
    setGroup: (group, data, year) =>
        dispatch(setGroup(group, data, year)),
    setStudent: (data, e, year, group, showStudent) =>
        dispatch(setStudent(data, e, year, group, showStudent)),
    resetForm: () => dispatch(resetForm()),
    setAuthenticated: value => dispatch(setAuthenticated(value))
});

Upvotes: 0

Views: 45

Answers (2)

markerikson
markerikson

Reputation: 67469

You can drastically simplify your code by using the "object shorthand" form of mapDispatch. Just define an object with those action creators, like:

const mapDispatchToProps = {
    fetchEvents,
    isLoadingCredentials,
    setCredentials,
    setYear,
    setGroup,
    setStudent,
    resetForm,
    setAuthenticated,
}

Also, I'd guess that you could probably consolidate some of those "set" actions down to a single "USER_FORM_UPDATED" action or something similar.

Upvotes: 1

Peter Ambruzs
Peter Ambruzs

Reputation: 8213

If data is a static object you can import it from the reducer. It will stay a pure function. But I would make my reducer as simple as possible and maybe I move this logic to the action creator. That's why we create action creators in the first place that they can contain logic as well.

For example:

import { data } from "../config/calendars.js";

export const setStudent = (value, year, group, showStudent) => {
  let studentName = data
    .find(option => {
      return option.id == year;
    })
    .options.find(option => {
      return option.id == group;
    })
    .options.find(option => {
      return option.id == value;
    }).label;

  return {
    type: "SET_STUDENT",
    student: value,
    label: studentName
  };
}

Upvotes: 0

Related Questions