Skip to content

Instantly share code, notes, and snippets.

@sergey-sign
Last active October 17, 2016 13:17
Show Gist options
  • Save sergey-sign/dbf0321f90a88c74ea5b4d16d38f3648 to your computer and use it in GitHub Desktop.
Save sergey-sign/dbf0321f90a88c74ea5b4d16d38f3648 to your computer and use it in GitHub Desktop.
#
# short action name: constans for this module only
# actions is not object: we can't use dispatch(@nextAction()), but without fat arrow
# _.assign instead Object.assign: without object-polyfill
_ = require 'lodash'
{getOrders} = require 'DataProvider/orders'
MODULE_NAME = 'omBulk'
SET_ERRORS = "#{MODULE_NAME}.SET_ERRORS"
LOADING_START = "#{MODULE_NAME}.LOADING_START"
LOADING_END = "#{MODULE_NAME}.LOADING_END"
listPromise = null
setError = (e)-> (dispatch)->
listPromise?.cancel()
data = {errors: {}, error: ''}
if _.hasIn(e, 'res.body.errors')
data.errors = e.res.body.errors
else
data.error = _.has(e, 'message') && e.message || 'Unknown error'
dispatch {type: SET_ERRORS, data}
#-------------------------------------- actions ------------------------------
loadOrders = (ids)-> (dispatch)->
listPromise?.cancel()
dispatch type: LOADING_START
listPromise = getOrders(ids)
.then (results)->
{orders} = results
dispatch(type: LOADING_END, orders, ids)
.catch (e)-> dispatch setError(e)
# call in componentWillUnmount
cancelRequests = ->
listPromise?.cancel()
#-------------------------------------- reducer ------------------------------
initialState =
error: '' # 50x
errors: {} # 40x
isLoading: false
ids: []
orders: []
OmBulkReducer = (state = initialState, action)->
switch action.type
when SET_ERRORS
_.assign {}, state, action.data, isLoading: false
when LOADING_START
_.assign {}, state, isLoading: true, error: '', errors: {}
when LOADING_END
{orders, ids} = action
_.assign {}, state, isLoading: false, orders, ids
else
state
module.exports =
actions:
loadOrders
cancelRequests
reducer: OmBulkReducer
{combineReducers} = require 'redux'
{routerReducer} = require 'react-router-redux'
reducers =
routing: routerReducer
omBulk: require('../modules/omBulk.ducks-modular-redux.examle.coffee').reducer
module.exports = combineReducers reducers
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment