I have an EnvironmentObject "User" that is responsible for sign-in and fetching user data. It's shared between all views in my app. Once the user data is loaded, the app changes views from "LoginView" to "HomeView." This User object contains data "userId."
I have another model called "Alerts" that should be initialized in the HomeView. Alerts will fetch alerts from the server, but it needs the userId from User to actually fetch. How can I share this data from User to Alert?
struct HomeView: View {
@EnvironmentObject var user: User
@ObservedObject var alerts: Alerts
init() {
if let id = user.id {
self.alerts = Alerts(userId: id)
}
}
Above I get the error 'self' used before all stored properties are initialized
. I believe there is something fundamental here that I am not understanding about SwiftUI or my model designs are problematic (each model is capable of using an API class to make calls to the server).
Edit: I've found a similar question here:
Swiftui - How do I initialize an observedObject using an environmentobject as a parameter?
But the answer (to create a nested view) seems hacky. Is this what SwiftUI intended or is there a more proper pattern used to accomplish this?