I have a view called FormView
which has its own VM called FormViewModel
. In this VM I have a method which adds a dictionary to Firestore. Alongside with some variables coming from the View, so from the user input, I need to add to Firestore also some User
specific details like its uid
and other properties which I have stored in the SessionStore
.
I'm doing this by passing to the add()
method of my VM the actual session. Is it ok to pass an EnvironmentObject to a ViewModel or should I just pass only my User
model stored inside SessionStore?
Which is the best approach to achieve smth like this? I have several similar scenarios in which my VM need properties stored in the User
model or even in SessionStore
(some computed properties)
struct FormView: View {
@EnvironmentObject var sessionStore: SessionStore
@ObservedObject var formViewModel = FormViewModel()
@State var favoriteMovie: String = ""
@State var favoriteTvShow: String = ""
var body: some View {
Button("add") {
self.formViewModel.add(sessionStore: sessionStore, favoriteMovie: favoriteMovie, favoriteTvShow: favoriteTvShow)
}
}
}
class FormViewModel: ObservableObject {
func add(sessionStore: sessionStore, favoriteMovie: String, favoriteTvShow: String) {
let details: [String: Any] = [
"ownerID": sessionStore.user.uid,
// other stuff from sessionStore here
"favoriteMovie": favoriteMovie,
"favoriteTvShow": favoriteTvShow
]
firestoreService.addDocument(details)
}
}
class SessionStore: ObservableObject {
var handle: AuthStateDidChangeListenerHandle?
@Published var user: User?
func listen() {
handle = Auth.auth().addStateDidChangeListener({ (auth, user) in
self.user = user
})
}
}