My SwiftUI app consists of different views with their own view models which handle data fetching etc. This works fine in the simulator, but I'd really like to be able to use previews and have each view appear in it's different state (loading, success, error etc.)
Here's a simple example of how a page might be built:
import SwiftUI
import Observation
@Observable
class TestViewModel {
enum State {
case loading
case success
}
private(set) var state = State.loading
func loadData() async {
// Make async network request here and update state
}
}
struct TestView: View {
@State private var viewModel = TestViewModel()
var body: some View {
Group {
switch viewModel.state {
case .loading: Text("Loading...")
case .success: Text("Success!")
}
}.task {
await viewModel.loadData()
}
}
}
#Preview {
TestView()
}
How would I go about mocking the view model/network response for previews?
stateproperty)? Apologies if I'm missing something obvious