Why would I use Redux Promise Middleware over Redux Promise?

9.9k Views Asked by At

I've used Redux Promise, but it seems Redux Promise Middleware has more functionality like dispatching multiple actions with "PENDING" or "FULFILLED" appended.

Why would I use one over the other?

2

There are 2 best solutions below

0
On BEST ANSWER

I personally prefer Redux Promise Middleware as middleware as it enables optimistic updates; dispatches pending, fulfilled and rejected actions; and works well with with Redux Thunk to chain async actions.

For example, you can use actions with _PENDING and _FULFILLED in reducers and update the UI with progress bar and similar.

0
On

There is an alternative to Redux Pomise Middleware. Redux Auto has the same API as redux-promise-middleware and comes with a bunch of utility patterns under the hood to reduce the boilerplate you need to write.

The idea is to have each action in a specific file. co-locating the server call in the file with reducer functions for "pending", "fulfilled" and "rejected". This makes handling promises very easy.

It also automatically attaches a helper object (called "async") to the prototype of your state, allowing you to track in your UI, requeste transitions.

Example:

data/serverThing.js

export function pending (posts, payload){
  return posts
}

export function fulfilled (posts, payload, result){
  return result.serverResponse
}

export function rejected (posts, payload, error){
  return posts;
}

export function action (payload) {
  return Promise.resolve({serverResponse: [1,2,3,4]})
}

UI

import React  from "react"
import actions from 'redux-auto'
import { connect } from 'react-redux'

class Foobar extends Component {

  const currentLoadingData = this.props.data.async.serverThing;

  if(currentLoadingData instanceof Error){
    var data = currentLoadingData.message
  } else if(true === currentLoadingData ){
    var data = "Loading..."
  } else {
    var data = this.porps.data.join();
  }

  render () {
    return (
      <div>
        <button onClick={()=>actions.data.serverThing()}>Do something!</button> 
        { data }
      </div>
    )
  }
}

const mapStateToProps = ( { data }) => {
  return { data }
};

export default connect( mapStateToProps )(Foobar);

To understand the above source. redux-auto automatically creates actions and wires them to reduces based on the file structure. Where the folder name becomes the name of the property on the state. The files within a folder are actions to be performed on that part of the state.

Here is a complete redux-auto: helloworld project