Passing Functions or Strings

Let's discuss the possibilities of passing action creator or type constant to our functions.

A common dilemma when using the API middleware approach is deciding whether the onSuccess parameter should be an action creator:

import { setUserData } from '../actions/users';

const fetchUser = id => ({
  type: API,
  payload: {
    url: `/user/${id}`,
    onSuccess: setUserData
  }
});

or a type constant:

import { SET_USER_DATA } from '../constants/actionTypes';

const fetchUser = id => ({
  type: API,
  payload: {
    url: `/user/${id}`,
    onSuccess: SET_USER_DATA
  }
});

The difference between these approaches is in the way the API middleware dispatches an action once a network request is resolved:

//Receiving an action creator
axios.get(url)
   .then(({ data }) => dispatch(onSuccess(data)));
// Receiving an action type
axios.get(url)
   .then(({ data }) => dispatch({ type: onSuccess, payload:  data }));

Both approaches have their pros and cons. Passing an action type makes actions serializable and thus easier to output to logs and debug visually. However, because this approach separates actions from network call results, it might be harder to follow the flow of side effects created by the actions.

Get hands-on with 1400+ tech skills courses.