} // This action does not have state and is a mere marker of "X happened": enum CounterAction: Action { case increase case decrease } func appReducer(action: Action, state: AppState?) -> AppState { var state = state ?? AppState() if let counterAction = action as? CounterAction { switch counterAction { case .increase: state.counter += 1 case .decrease: state.counter -= 1 } } return state } let store = Store( reducer: appReducer, state: AppState(), middleware: []) store.dispatch(CounterAction.increase)
which needs to know the type of your `State`. let thunkMiddleware: Middleware<AppState> = createThunkMiddleware() // Note that it can perfectly live with other middleware in the chain. let store = Store<AppState>(reducer: reducer, state: nil, middleware: [thunkMiddleware])
effects, access the current state of the store, and dispatch new actions, as if it were a ReSwift middleware. let thunk = Thunk<AppState> { dispatch, getState in if getState!.loading { return } dispatch(RequestStart()) api.getSomething() { something in if something != nil { dispatch(RequestSuccess(something)) } else { dispatch(RequestError()) } } } // As the thunk type conforms to the `Action` protocol, you can dispatch it as usual, without having to implement an overload of the `dispatch` function inside the ReSwift library. store.dispatch(thunk)
want to pass on parameters func thunkWithParams(_ identifier: Int) -> Thunk<AppState> { return Thunk<MyState> { dispatch, getState in guard let state = getState() else { return } if state.loading { return } api.getSomethingWithId(identifier) { something in if something != nil { dispatch(RequestSuccess(something)) } else { dispatch(RequestError()) } } } } // You can do the same with the Thunk that requires parameters, like so store.dispatch(thunkWithParams(10))