R
R
Ramil2018-03-16 17:42:23
Angular
Ramil, 2018-03-16 17:42:23

How to make actions asynchronous in Redux + AngularJS?

I got one project. I'm trying to upgrade it and decided to add redux to it.
Stuck at one point. I get the error "Actions must be plain objects. Use custom middleware for async actions". I understand what she means. But I don’t understand why it occurs.
This is how I register the store in the application config:

$provide.factory('injectMiddleware', ($http) => {
  return thunk.withExtraArgument({ $http })
})

$ngReduxProvider.createStoreWith(
  store,
  ['injectMiddleware'],
  process.env.DEBUG
    && window.__REDUX_DEVTOOLS_EXTENSION__
    && [window.__REDUX_DEVTOOLS_EXTENSION__()]
)

This is how the reducer with actions looks like:
const initialState = {
  current: null
}
export const UsersReducer = (state = initialState, action) => {
  switch (action.type) {
    case 'SET_CURRENT':
      return {
        ...state,
        ...action.payload
      }
    default:
      return state
  }
}
export const UsersActions = {
  async getCurrentUser () {
    return async (dispatch, getState, { $http }) => {
      await Promise.resolve({
        type: 'SET_CURRENT',
        payload: { name: 'Вася' }
      })
    }
  }
}

Controller:
import { UsersActions } from 'storage/users'
class HomeController {
  constructor ($ngRedux) {
    this.unsubscribe = $ngRedux.connect(this.mapState, UsersActions)(this)
  }
  $onInit () {
    this.getCurrentUser()
  }
  $onDestroy () {
    this.unsubscribe()
  }
  mapState (state) {
    return {
      currentUser: state.user.current
    }
  }
}

I understand that the problem is not new. Google is full of people who have come across it. But for some reason, in my case, all their solutions did not help.
For asynchrony in actions, I used the redux-thunk middleware. I debugged the code and noticed that in this middleware, the action comes as an object, but it should as a function. How can this be if my action returns a function, it's not clear to me?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question