angular-redux / ng-redux

Angular bindings for Redux
MIT License
1.16k stars 177 forks source link

Question: async dispatch / thunk advice requested #213

Closed dusty closed 5 years ago

dusty commented 5 years ago

I ran into an issue with thunk and dev tools. Before I realized that 3.5.2 still works for that, I tried just injecting $ngRedux into a factory and using $ngRedux.dispatch, rather than using a thunked action creator.

Going this route, I no longer used mapDispatchToTarget and just injected the service and used it like I would have pre-redux.

Question: Is there anything wrong with this method that I'm overlooking? It seems so simple. :)

PS: Love the library, thanks.

Here is an example with the thunk methods commented out.

;(function() {
  angular.module('app.store').factory('UsersAction', UsersAction)

  function UsersAction($http, $ngRedux) {
    const url = 'https://jsonplaceholder.typicode.com/users'

    // const getUsers = () => dispatch => {
    //   return $http
    //     .get(url)
    //     .then(res => dispatch({ type: 'SET_USERS', payload: res.data }))
    // }

    const getUsers = () => {
      return $http
        .get(url)
        .then(res =>
          $ngRedux.dispatch({ type: 'SET_USERS', payload: res.data })
        )
    }

    return { getUsers }
  }
})()

Then in the component

let unsubscribe

ctrl.$onInit = function() {
  const mapState = ({ users }) => ({ users })
  unsubscribe = $ngRedux.connect(mapState)(ctrl)
  UserAction.getUsers()
  // unsubscribe = $ngRedux.connect(mapState, UsersAction)(ctrl)
  // ctrl.getUsers()
}

ctrl.$onDestroy = function() {
  unsubscribe()
}