Skip to content

How can I reduce this async action/reducer boilerplate pattern? #1661

Closed
@abrkn

Description

@abrkn

I have thousands of lines along the lines of:

const thing = (state = {}, action) => {
  if (action.type === 'FETCH_THING') {
    if (!action.status) {
      return {
        ...state,
        fetchThingStatus: 'pending',
        fetchThingStatusAt: +new Date,
        fetchThingStatusError: null,
      };
    }

    if (action.status === 'success') {
      return {
        ...state,
        fetchThingStatus: action.status,
        fetchThingStatusAt: +new Date,
        fetchThingStatusError: null,
      };
    }

    if (action.status === 'error') {
      return {
        ...state,
        fetchThingStatus: action.status,
        fetchThingStatusAt: +new Date,
        fetchThingStatusError: action.error.stack,
      };
    }
  }

  return state;
};

const fetchThing = () => (dispatch, getState) => {
  const action = {
    type: 'FETCH_THING',
  };

  dispatch(action);

  fetchThing({
    /// ...
  })
    .then(() => {
      dispatch({
        ...action,
        status: 'success',
      });
    })
    .catch(error => {
      dispatch({
        ...action,
        error: error.message,
      });
    });
};

const shouldFetchThing = (state) => {
  const { thing } = state;

  return thing.fetchThingStatus !== 'pending' &&
    (!thing.fetchThingStatusAt || +new Date - thing.fetchThingStatusAt > 10 * 60e3);
};

const thingMiddleware = ({ getState, dispatch }) => {
  setInterval(() => {
    if (shouldFetchThing(getState())) {
      dispatch(fetchThing());
    }
  }, 1e3);

  return next => action => next(action);
};

The above example is the simplest case. In other cases there are updates with more complicated optimistic concurrency.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions