state.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. /** @module */
  2. /**
  3. * state.js
  4. *
  5. * The application uses Redux to handle the state.
  6. * Redux has a **store** which allows access to the one big state of the
  7. * modules. It also has a dispatcher, which receives actions and calls
  8. * reducer functions to act on them.
  9. *
  10. * The store handles all state changes. For that, a module
  11. * defines **action creators**, which are helper functions generating action
  12. * objects. An action object contains a 'type' property, which gives the action
  13. * a name, and a payload, which will be processed.
  14. *
  15. * The processing unit is called a **reducer** and is exported as 'reducer' in
  16. * this file. It is a function which receives
  17. * the current state and an action and returns the processed state. It is good
  18. * practice, that the reducer doesn't change the state (which is passed by
  19. * reference), but creates a modified state and returns it. Also, the reducer
  20. * should return immediately. If an asynchronous operation has to be executed,
  21. * it is handled through redux-sagas, which is basically a concurrent process
  22. * triggered by a reducer, which generates a new action once it's completed.
  23. *
  24. * Action creators (defined as 'actions' in this file) are bound to the
  25. * Redux dispatcher in 'index.js'. When they are called, the dispatcher sends
  26. * the greated action to **all** reducers. This module, and other modules which
  27. * change the state of this module, use these action creators to modifiy the
  28. * state.
  29. *
  30. * This file exports everything which is necessary to set up and operate the
  31. * state of this module.
  32. * - actions
  33. * - reducers
  34. * - state
  35. * - sagas
  36. **/
  37. // Import NAME and DATA to be able to create action creators */
  38. import { NAME, DATA } from './constants'
  39. import { primary } from './initialData'
  40. import { delay } from 'redux-saga'
  41. import { call, put, takeEvery } from 'redux-saga/effects'
  42. /** state definition */
  43. /** It is generally easier to not have another object here. */
  44. export const state = []
  45. console.log('State state', state)
  46. /** actionTypes define what actions are handeled by the reducer. */
  47. const actionTypes = {}
  48. export const actionCreators = {}
  49. // Generate default actionsTypes CREATE, UPDATE, REMOVE
  50. DATA.forEach(dataItem => {
  51. ['create', 'update', 'remove'].forEach(action => {
  52. // The Redux convention is to name action types e.g. demo_module/UPDATE
  53. // For action creators, we define here the name e.g. removePrimary(id, data)
  54. // where id is the element id and data is the element itself.
  55. const actionType = `${action.toUpperCase()}_${dataItem.toUpperCase()}`
  56. const actionName = `${action}${dataItem[0].toUpperCase()}${dataItem.substring(1)}`
  57. actionCreators[actionName] = (id, data) => { return { type: `${NAME}/${actionType}`, id, data } }
  58. actionTypes[actionType] = `${NAME}/${actionType}`
  59. })
  60. })
  61. // Add specific action creators here:
  62. actionCreators['loadSamples'] = () => { return { type: `${NAME}/LOAD_SAMPLES` } }
  63. actionTypes['LOAD_SAMPLES'] = `${NAME}/LOAD_SAMPLES`
  64. console.log('State actionTypes, actionCreators', actionTypes, actionCreators)
  65. /** reducer is called by the redux dispatcher and handles all component actions */
  66. /** The module's root reducer tries to split up the state and let specific
  67. * specialized reducers handle the work. This is not necessary, but more
  68. * convenient and readable. */
  69. // In this example it is assumed, that the secondary items have a key 'primaryId',
  70. // which references the primary data element.
  71. export function reducer (state = [], action) {
  72. // find the primary data element with the matching id.
  73. const idx = state.findIndex(elem => {return (action.id === elem.id)})
  74. console.log(`Entering demo_module root reducer.`, state, action, idx)
  75. let nextState
  76. if (action.type.match(/SECONDARY/)) {
  77. // leave immediately, if no idx was found (operations on secondary not valid if there's no primary)
  78. if (idx < 0) {
  79. return state
  80. }
  81. console.log(`Using secondary reducer.`)
  82. const subState = state.secondary
  83. const reducedState = secondaryReducer(subState, action)
  84. nextState = {
  85. ...state,
  86. secondary: reducedState
  87. }
  88. console.log('Leaving demo_module root reducer', subState, reducedState, nextState)
  89. return nextState
  90. }
  91. switch (action.type) {
  92. case actionTypes.CREATE_PRIMARY:
  93. nextState = [ ...state, action.data ]
  94. console.log('Creating primary', state, nextState)
  95. return nextState
  96. case actionTypes.UPDATE_PRIMARY:
  97. console.log(idx, state[idx], action.data, {...state[idx], ...action.data})
  98. nextState = [ ...state.slice(0, idx), {...state[idx], ...action.data}, ...state.slice(idx + 1) ]
  99. console.log('Updating primary', state, nextState)
  100. return nextState
  101. case actionTypes.REMOVE_PRIMARY:
  102. console.log('wtf')
  103. nextState = [ ...state.slice(0, idx), ...state.slice(idx+1) ]
  104. console.log('Removing primary', state, nextState)
  105. return nextState
  106. case actionTypes.LOAD_SAMPLES:
  107. nextState = primary
  108. console.log('Loading sample data', state, nextState)
  109. return nextState
  110. default:
  111. return state
  112. }
  113. }
  114. function secondaryReducer (state = [], action) {
  115. console.log(`Entering secondary reducer.`, state, action)
  116. const idx = state.findIndex(elem => {return (action.id === elem.id)})
  117. let nextState
  118. switch (action.type) {
  119. case actionTypes.CREATE_SECONDARY:
  120. nextState = [ ...state, action.data ]
  121. console.log(`Creating secondary.`, state, nextState)
  122. return nextState
  123. case actionTypes.UPDATE_SECONDARY:
  124. nextState = [ ...state.slice(0, idx), action.data, ...state.slice(idx + 1)]
  125. console.log(`Updating secondary.`, idx, state, nextState)
  126. return nextState
  127. case actionTypes.REMOVE_SECONDARY:
  128. nextState = [ ...state.slice(0, idx), ...state.slice(idx + 1) ]
  129. console.log(`Removing secondary.`, idx, state, nextState)
  130. return nextState
  131. default:
  132. return state
  133. }
  134. }
  135. console.log('State reducer', reducer)
  136. /** sagas are asynchronous workers (JS generators) to handle the state.
  137. // Worker
  138. export function * incrementAsync () {
  139. try {
  140. const data = yield call(Api.isIncrementOk)
  141. yield put({ type: 'INCREMENT_SUCCESS', data })
  142. } catch (error) {
  143. yield put({ type: 'INCREMENT_FAIL', error})
  144. }
  145. }
  146. // Watcher (intercepts INCREMENT_REQUEST, dispatches INCREMENT_SUCCESS or INCREMENT_FAIL in return.)
  147. export function * watchIncrementAsync () {
  148. yield takeEvery('INCREMENT_REQUEST', incrementAsync)
  149. }
  150. // export all sagas in parallel
  151. function * sagas () {
  152. yield takeEvery('INCREMENT_REQUEST')
  153. yield takeEvery('DECREMENT_REQUEST')
  154. } */
  155. export const sagas = null
  156. console.log('State sagas', sagas)