zloctb
zloctb

Reputation: 11186

Correct pattern for async dispatch

Please help me, is it correct pattern for async dispatch with redux thunk?

//actions types
const ADD_ARTIST = 'ADD_ARTIST'

// action
function AddArtist(val){
  return {
    type: ADD_ARTIST,
    payload:val
  }
}


//some async events 
function async1(id){
  return fetch(.....)
}

function async2(id){
  return fetch(.....)
}

function async3(id){
  return fetch(.....)
}

function auth(id) {
  return function (dispatch) {
    async1(10).then( (v) =>  dispatch(AddArtist(v)) );
    Promise.all([
      async2(26),
      async3(51),
    ]).then(
          (v) => dispatch(AddArtist(v[0] + v[1] )
      ));
  }
}


var ViewWrapper = connect(
  state => ({
    playlist: state.playlist,
    artist: state.artist,
  }),
  dispatch => (
    {
      dispatch,
      auth: bindActionCreators(auth, dispatch)
  })

)(View);

and button :

  <input type='button' onClick={() => 
this.props.dispatch( this.props.auth() ) }   value='dispatch mapDispatch>>>>>>>' />

Upvotes: 0

Views: 48

Answers (1)

xkeshav
xkeshav

Reputation: 54022

according to redux documentation, this looks fine but you also apply some code to error handling.

here you can write the better way

function auth(id) {
     return ((dispatch) => async1(10)
               ).then( (v) => dispatch(AddArtist(v))
               ).then( () => 
                 Promise.all([
                    async2(26),
                    async3(51),
               ])
              ).then( (v) => dispatch(AddArtist(v[0] + v[1])) 
             )
      )
}

Upvotes: 1

Related Questions