1

I'm new to Redux, I've seen a lot of people using some Middleware to handle asynchronous.

My question is, I can just do this:

fetch(myAPI)
  .then(res => res.json())
  .then(res => {
    dispatch({
      type: 'MY_ASYNC_ACTION',
      res
    })
  })

I could just wait for the promise to resolve then dispatch my synchronous action.

What's the benefit of using middleware to handle asynchronous in Redux instead of just waiting for the promise to resolve?

I've seen lot's of tutorials about Redux, none of them wait the promise to resolve, what did I miss?

Joseph
  • 3,974
  • 7
  • 34
  • 67
  • using e.g. redux-thunk does not excuse you from dispatching an action once the promise is resolved but it means that action itself is dispatched asynchronously. – Tomasz Czechowski Jul 24 '19 at 09:52

1 Answers1

1

What's the benefit of using middleware to handle asynchronous in Redux instead of just waiting for the promise to resolve?

Consider middleware as a middleman between your actions and your reducers. That can give you the flexibility of performing async operations (e.g. fetch/other API calls) without stopping the main thread (your flow). And show your users a fallback UI to indicate something is happening in the background.

A simple use case: Your user might want to see some data, and do other stuff while it is fetched. Without a middleware, your user might wait for something to happen (till your fetch resolve), but don't have any indicator to what is happening.

Check Redux Async Flow for more details And Redux-Saga middleware for handling async flows in your application.

Tomer
  • 1,521
  • 1
  • 15
  • 26