1

I've always used redux-thunk or some sort of middleware that grants me access to dispatch/getState, but I have a question that keeps bugging me. Why using that when we can import our store and call store.dispatch()/store.getState().

Later edit:

As a quick example, here's the original code:

function loadData(userId) {
  return dispatch => fetch(`http://data.com/${userId}`) // Redux Thunk handles these
    .then(res => res.json())
    .then(
      data => dispatch({ type: 'LOAD_DATA_SUCCESS', data }),
      err => dispatch({ type: 'LOAD_DATA_FAILURE', err })
    );
}

Basically, what I'm asking is why is it bad to rewrite this as:

import store from 'our-store';

function loadData(userId) {
  return fetch(`http://data.com/${userId}`)
    .then(res => res.json())
    .then(
      data => store.dispatch({ type: 'LOAD_DATA_SUCCESS', data }),
      err => store.dispatch({ type: 'LOAD_DATA_FAILURE', err })
    );
}
  • Thunks allow you to do more within them than just performing a vanilla dispatch. Say you want to fetch from an API and either dispatch the success or failure response, with a thunk you can dispatch after an async event, and just connect the thunk to your component. – lux Apr 11 '20 at 16:36
  • Hm, i don't see how thunks help you in this scenario. What you describe is a whole new middleware, right? And in middlewares you have by default access to the store, so no need for redux-thunk. And you might not need dispatch since you have ```next()```. – Bogdan Mihai Apr 11 '20 at 17:27
  • 1
    Does this answer your question? [Why do we need middleware for async flow in Redux?](https://stackoverflow.com/questions/34570758/why-do-we-need-middleware-for-async-flow-in-redux) – lux Apr 11 '20 at 20:51
  • I voted for closure based on duplication. This question has been asked many times over. – lux Apr 11 '20 at 20:52
  • I've update my question. Can you take a look, please? – Bogdan Mihai Apr 12 '20 at 07:34
  • Because thunks give access to redux via dependency injection, which is a superior pattern to importing state. – lux Apr 13 '20 at 04:28
  • 1
    You were right, @lux. Thank you for the link above, I found my answer there. – Bogdan Mihai Apr 14 '20 at 06:54

0 Answers0