2

Redux documentation says that to do async calls—which would typically involve an action indicating the start of the async call, and a later action indicating its completion—I should use the "thunk" middleware. This allows me to write "actions creators" like this:

function fetchPosts(reddit) {
  return dispatch => {
    dispatch(requestPosts(reddit))
    return fetch(`http://www.reddit.com/r/${reddit}.json`)
      .then(response => response.json())
      .then(json => dispatch(receivePosts(reddit, json)))
  }
}

(Here requestPosts and receivePosts are action creators.)

The thunk middleware allow me to dispatch the (function) output of fetchPosts, e.g.,

store.dispatch(fetchPosts('reactjs')).then(() =>
  ...

But why involve middleware at all? Why is this better than just writing my own fetchPost function using the global store, like this:

function fetchPosts(reddit) {
  store.dispatch(requestPosts(reddit));
  return fetch(`http://www.reddit.com/r/${reddit}.json`)
      .then(response => response.json())
      .then(json => store.dispatch(receivePosts(reddit, json)))
  }
}

Obviously, I can't dispatch this function, but that doesn't seem terribly important. What am I missing?

Søren Debois
  • 5,598
  • 26
  • 48
  • Possible duplicate of [What are the benefits of using thunk middleware in redux over using regular functions as async action creators?](http://stackoverflow.com/questions/34713466/what-are-the-benefits-of-using-thunk-middleware-in-redux-over-using-regular-func) – David L. Walsh Jan 18 '16 at 01:05
  • 4
    Possible duplicate of [Why do we need middleware for async flow in Redux?](http://stackoverflow.com/questions/34570758/why-do-we-need-middleware-for-async-flow-in-redux) – user5325596 Jan 18 '16 at 15:51
  • Oh. Sorry. @user5325596 's reference is The more helpful one. – Søren Debois Jan 18 '16 at 17:58

0 Answers0