Last active
April 3, 2021 11:30
-
-
Save fabstu/17ecfff9f327654eb69fb1ae92b2a0fb to your computer and use it in GitHub Desktop.
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 ComposableArchitecture | |
indirect enum AppAction { | |
case value(id: String, action: ValueAction) | |
case push | |
case delete(IndexSet) | |
case deleteFirst | |
} | |
struct AppState: Equatable { | |
var values: IdentifiedArrayOf<Value> = [] | |
} | |
class AppEnvironment {} | |
struct Value: Identifiable, Equatable { | |
let id: String | |
var text: String | |
} | |
enum ValueAction { | |
case setText(_ text: String) | |
} | |
let appReducer = Reducer<AppState, AppAction, AppEnvironment>.combine( | |
Reducer { (state: inout AppState, action: AppAction, environment: AppEnvironment) in | |
switch action { | |
case .push: | |
let date = Date() | |
state.values.append( | |
Value(id: UUID().uuidString, text: "\(date)") | |
) | |
return .none | |
case let .delete(indexSet): | |
state.values.remove(atOffsets: indexSet) | |
return .none | |
case .deleteFirst: | |
state.values.remove(at: 0) | |
return .none | |
case .value(id: let id, action: let action): | |
switch action { | |
case let .setText(newValue): | |
state.values[id: id]!.text = newValue | |
return .none | |
} | |
} | |
} | |
) |
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 ComposableArchitecture | |
struct AppView: View { | |
let store: Store<AppState, AppAction> | |
var body: some View { | |
VStack{ | |
HStack{ | |
WithViewStore(store) {viewStore in | |
Button("Push") { | |
viewStore.send(.push, animation: .default) | |
} | |
Button("Delete") { | |
viewStore.send(.deleteFirst) | |
} | |
} | |
} | |
HStack{ | |
ScrollViewReader { scrollView in | |
ScrollView{ | |
ForEachStore( | |
store.scope( | |
state: \.values, | |
action: AppAction.value(id:action:) | |
), | |
content: ValueView.init | |
) | |
} | |
} | |
} | |
} | |
} | |
} | |
struct ValueView: View { | |
let store: Store<Value, ValueAction> | |
var body: some View { | |
WithViewStore(store) { (viewStore: ViewStore<Value, ValueAction>) in | |
HStack{ | |
Text(viewStore.state.id) | |
TextField("text", text: viewStore.binding(get: \.text, send: ValueAction.setText)) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment