Hello my Xcode app fetches the current user from my database and stores their data in a User struct. And this data is needed for other portions of the app. I use an EnvirnmentObject to translate this data to other views. But the problem Im running in is: if I modify a variable in the struct of the current user in one view then navigate to another view this change is not observed in the new view. I don't think you can make @Published vars static, but what's another approach so that if I modify the variable "followers" for example in one view then all the others views will also have this change. I want to do this so I don't have to fetch the current user from the database every time I make changes to the current user.
getting the current user:
import SwiftUI
import Firebase
class AuthViewModel: ObservableObject{
private let service = UserService()
@Published var currentUser: User?
init(){
self.fetchUser()
}
func fetchUser(){
service.fetchUser() { user in
self.currentUser = user
}
}
}
view 1
import SwiftUI
struct viewOne: View {
@EnvironmentObject var authViewModel: AuthViewModel
var body: some View {
VStack(alignment: .center, spacing: 2){
AuthViewModel.currentUser.followers = 25
}
}
}
view 2 - change in followers var is not seen
import SwiftUI
struct viewOne: View {
@EnvironmentObject var authViewModel: AuthViewModel
var body: some View {
VStack(alignment: .center, spacing: 2){
Text("\(AuthViewModel.currentUser.followers)") // not 25
}
}
}