-1

Most of my redux actions are 'fetch some data from the database, here's the authentication token', and they for the most part look the same, like this:

action creator

export const fetchDashboard = jwt => async dispatch => {
  dispatch(fetchDashboardRequest());
  try {
    const response = await axios.get(
      DASHBOARD_ENDPOINT,
      {
        headers: {
          Authorization: `Bearer ${jwt}`,
        },
      }
    );

    dispatch({
      type:
        Action.FETCH_DASHBOARD_SUCCESS,
      payload: response.data.dashboard,
    });
  } catch (error) {
    dispatch({
      type:
        Action.FETCH_DASHBOARD_FAILURE,
      payload: flatmapErrors(
        error.response.data
      ),
    });
  }
};

reducer

export default (
  state = initialState,
  action
) => {
  switch (action.type) {
  case Action.FETCH_DASHBOARD_SUCCESS:
    return {
      ...state,
      ...action.payload
    };

  case Action.FETCH_DASHBOARD_FAILURE:
    return {}

  case Action.DASHBOARD_CLEAR_DATA : {
    return {}; 
  }
  default:
    return state;
  }
};

This is a fair bit of boilerplate, and I end up using VSCode snippets to generate it.

I end up editing the endpoint constant, for some, the headers might change, and there might be some parsing on the data structure, but for the most part, the API gives me the data as I need it.

But over more and more actions, I'm worried that this isn't DRY, and that a refactor later might be a pain.

Is this a worth while concern, or should I consider this just necessary boilerplate?

0

This is violating DRY principle, but whether or not you should fix it is ultimately dependent upon whether or not you think you'll need to add more in the future, otherwise it's YAGNI (You Aren't Gonna Need It).

A good general rule of thumb is if you have three virtually duplicate pieces of code, chances are you're probably going to need a fourth, so you should take the effort towards finding aspects in common and abstracting behavior into a single common method.

If you're a purist like me, you may want to do it anyway to save yourself the hassle later, but know that it isn't strictly necessary until you think the behavior is generalizable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.