meow/Meow/Sources/Facts/FactsView.swift

50 lines
1.4 KiB
Swift

//
// FactsView.swift
// Facts
//
import SwiftUI
import Foundation
import ComposableArchitecture
/// A view that displays either a progress spinner, a list of cat facts provided by an underlying feature reducer, or
/// an error message, depending on the state. Supports pull-to-refresh.
public struct FactsView: View {
let store: StoreOf<FactsFeature>
public init(store: StoreOf<FactsFeature>) {
self.store = store
}
public var body: some View {
VStack {
switch store.state.mode {
case .notLoaded:
EmptyView()
case .loading:
ProgressView()
case let .loaded(facts):
List(facts, id: \.self) { fact in
Text(fact)
}
case let .error(error):
Text(error.localizedDescription)
}
}
.refreshable {
// Tie the lifecycle of the PTR to the effect.
// https://github.com/pointfreeco/swift-composable-architecture/discussions/2542
await Task { await store.send(.pulledToRefresh).finish() }.value
}
.onAppear {
store.send(.viewAppeared)
}
}
}
#Preview {
FactsView(store: .init(initialState: FactsFeature.State(mode: .loaded(facts: ["One", "Two", "Three"]))) {
FactsFeature()
})
}