Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 0. create the shape of the managed part of state
- interface Counter {
- value: number
- }
- const defaultCounterState: Counter = { value: 0 }
- interface AppState {
- counter: Counter
- }
- const defaultAppState: AppState = {
- counter: defaultCounterState,
- }
- // 1. interface for action creator to handle increment
- interface HandleIncrementAction {
- type: "HANDLE_INCREMENT",
- }
- // 2. action creator to handle increment
- const handleIncrement = (): HandleIncrementAction => ({
- type: "HANDLE_INCREMENT"
- })
- // 3. a listener in the root saga
- default function* root(): {} {
- yield [
- takeEvery("HANDLE_INCREMENT", handleIncrement)
- ]
- }
- // 4. a selector function to get a specific part of Redux state
- function selectCounter(state: AppState): Counter {
- return state.counter
- }
- // 5. a saga function to handle side effects and/or payload
- function* handleIncrement(action: HandleIncrementAction): {} {
- // uses the selector defined in step 4
- const counter = yield select(selectCounter)
- const newValue = counter.value + 1
- // uses the action/interface defined in steps 6 and 7
- yield put(actions.setCounter(newCounter))
- }
- // 6. interface for action creator to set new value in state
- interface SetCounter {
- type: "SET_COUNTER"
- value: number
- }
- // 7. action creator to set new value in state
- const setCounter = (value: number) => ({
- type: "SET_COUNTER",
- value,
- })
- // 8. a reducer listening for the action called in step 5
- function counter(
- state: Counter = defaultCounterState,
- action: SetCounterAction,
- ): number {
- switch (action.type) {
- case "SET_COUNTER":
- return { ...state, value: action.value }
- default:
- return state
- }
- }
- // 9. reducer is registered with the root reducer, and a store is created from it
- const rootReducer = redux.combineReducers({
- counter,
- })
- const store = createStoreWithMiddleware(rootReducer)
- sagaMiddleware.run(root())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement