2

What I have: View and ViewModel (as extension to View struct).
Both of them are use @EnvironmentObject of type AppState.
The problem is that my preview crashes due to this error:
Fatal error: No ObservableObject of type AppState found.
Commenting out lines in loadUser func saves from crash.

struct ProfileView: View {
    @EnvironmentObject var appState: AppState
    @ObservedObject var viewModel = ViewModel()
    ...
}
extension ProfileView {
    class ViewModel: ObservableObject {
        @EnvironmentObject var appState: AppState
        @Published var userVM = UserVM(.example)

        init() {
            loadUser()
        }

        func loadUser() {
            User.WebService.getSelf { user, errorMsg in
                DispatchQueue.main.async {
                    guard let user = user else {
                        /*self.appState.showingAlert = true
                        self.appState.alert = Alert(
                            title: Text("An error occured!"),
                            message: Text(errorMsg ?? "unknown error"))*/
                        return
                    }
                    self.userVM = UserVM(user)
                }
            }
        }
    }
}
struct ProfileView_Previews: PreviewProvider {
    static let viewModel = ProfileView.ViewModel()
    static var previews: some View {
        let appState = AppState()
        appState.activeScreen = .profile
        return ProfileView()
            .environmentObject(appState)
    }
}
4

0 回答 0