Advertisement
Guest User

Untitled

a guest
Feb 20th, 2019
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. // 0. create the shape of the managed part of state
  2. interface Counter {
  3. value: number
  4. }
  5.  
  6. const defaultCounterState: Counter = { value: 0 }
  7.  
  8. interface AppState {
  9. counter: Counter
  10. }
  11.  
  12. const defaultAppState: AppState = {
  13. counter: defaultCounterState,
  14. }
  15.  
  16. // 1. interface for action creator to handle increment
  17. interface HandleIncrementAction {
  18. type: "HANDLE_INCREMENT",
  19. }
  20.  
  21. // 2. action creator to handle increment
  22. const handleIncrement = (): HandleIncrementAction => ({
  23. type: "HANDLE_INCREMENT"
  24. })
  25.  
  26. // 3. a listener in the root saga
  27. default function* root(): {} {
  28. yield [
  29. takeEvery("HANDLE_INCREMENT", handleIncrement)
  30. ]
  31. }
  32.  
  33. // 4. a selector function to get a specific part of Redux state
  34. function selectCounter(state: AppState): Counter {
  35. return state.counter
  36. }
  37.  
  38. // 5. a saga function to handle side effects and/or payload
  39. function* handleIncrement(action: HandleIncrementAction): {} {
  40. // uses the selector defined in step 4
  41. const counter = yield select(selectCounter)
  42.  
  43. const newValue = counter.value + 1
  44.  
  45. // uses the action/interface defined in steps 6 and 7
  46. yield put(actions.setCounter(newCounter))
  47. }
  48.  
  49. // 6. interface for action creator to set new value in state
  50. interface SetCounter {
  51. type: "SET_COUNTER"
  52. value: number
  53. }
  54.  
  55. // 7. action creator to set new value in state
  56. const setCounter = (value: number) => ({
  57. type: "SET_COUNTER",
  58. value,
  59. })
  60.  
  61. // 8. a reducer listening for the action called in step 5
  62. function counter(
  63. state: Counter = defaultCounterState,
  64. action: SetCounterAction,
  65. ): number {
  66. switch (action.type) {
  67. case "SET_COUNTER":
  68. return { ...state, value: action.value }
  69. default:
  70. return state
  71. }
  72. }
  73.  
  74. // 9. reducer is registered with the root reducer, and a store is created from it
  75. const rootReducer = redux.combineReducers({
  76. counter,
  77. })
  78. const store = createStoreWithMiddleware(rootReducer)
  79. sagaMiddleware.run(root())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement