Created
March 5, 2022 17:22
-
-
Save SwiftyAlex/4a370b93e200658e164bfcbb84ad38bd to your computer and use it in GitHub Desktop.
TCA app make sure you have composable set
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
import Combine | |
import ComposableArchitecture | |
struct AppState: Equatable { | |
var count = 0 | |
} | |
enum AppAction: Equatable { | |
case decrementButtonTapped | |
case incrementButtonTapped | |
} | |
enum ExampleError: Error { | |
case example | |
} | |
struct AppEnvironment { | |
var mainQueue: AnySchedulerOf<DispatchQueue> | |
} | |
let appReducer = Reducer<AppState, AppAction, AppEnvironment> { state, action, environment in | |
switch action { | |
case .decrementButtonTapped: | |
state.count -= 1 | |
return .none | |
case .incrementButtonTapped: | |
state.count += 1 | |
return .none | |
} | |
} | |
class CounterViewModel: ObservableObject { | |
var viewStore: Store<AppState, AppAction> | |
init(viewStore: Store<AppState, AppAction>) { | |
self.viewStore = viewStore | |
} | |
} | |
let store = Store(initialState: AppState(), reducer: appReducer, environment: AppEnvironment(mainQueue: .main)) | |
let counterViewModel = CounterViewModel(viewStore: store) | |
struct CounterView: View { | |
@StateObject var viewModel: CounterViewModel | |
var body: some View { | |
WithViewStore(viewModel.viewStore) { store in | |
VStack { | |
Text("Count \(store.count)") | |
.font(.subheadline.weight(.bold)) | |
HStack { | |
Button(action: { store.send(.decrementButtonTapped)}, label: { Text("-") }) | |
Button(action: { store.send(.incrementButtonTapped) }, label: { Text("+") }) | |
} | |
} | |
} | |
} | |
} | |
struct ContentView: View { | |
var body: some View { | |
let store = Store(initialState: AppState(), reducer: appReducer, environment: AppEnvironment(mainQueue: .main)) | |
let counterViewModel = CounterViewModel(viewStore: store) | |
return VStack { | |
CounterView(viewModel: counterViewModel) | |
} | |
} | |
} | |
@main | |
struct MyApp: App { | |
var body: some Scene { | |
WindowGroup { | |
ContentView() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment