Skip to content

Instantly share code, notes, and snippets.

@ryo33
Last active January 4, 2017 00:14
Show Gist options
  • Save ryo33/c117058fe00b0000b3ab864a3a56fec7 to your computer and use it in GitHub Desktop.
Save ryo33/c117058fe00b0000b3ab864a3a56fec7 to your computer and use it in GitHub Desktop.
redux-thunk and redux-middlewares

gaearon/redux-thunk

These examples are not completely compatible about whether to call next(action).

incrementAsync

redux-thunk

function incrementAsync() {
  return dispatch => {
    setTimeout(() => {
      dispatch(increment());
    }, 1000);
  };
}

redux-middlewares

const INCREMENT_COUNTER_ASYNC = 'INCREMENT_COUNTER_ASYNC';

function incrementAsync() {
  return {
    type: INCREMENT_COUNTER_ASYNC
  };
}

const incrementAsyncMiddleware = createMiddleware(
  INCREMENT_COUNTER_ASYNC,
  ({ dispatch }) => {
    setTimeout(() => {
      dispatch(increment());
    }, 1000)
  }
);

incrementIfOdd

redux-thunk

function incrementIfOdd() {
  return (dispatch, getState) => {
    const { counter } = getState();

    if (counter % 2 === 0) {
      return;
    }

    dispatch(increment());
  };
}

redux-middlewares

const INCREMENT_COUNTER_IF_ODD = 'INCREMENT_COUNTER_IF_ODD';

function incrementIfOdd() {
  return {
    type: INCREMENT_COUNTER_IF_ODD
  };
}

const incrementIfOddMiddleware = createMiddleware(
  INCREMENT_COUNTER_IF_ODD,
  ({ getState }) => {
    const { counter } = getState();
    return counter % 2 === 1;
  },
  ({ dispatch }) => dispatch(increment())
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment