Ufuk Köşker
Ufuk Köşker

Reputation: 1480

Passing data with ObservableObject keyword

How can I move data to other screens with ObservableObject keyword? I save the data on the first page to the variable I created with the keyword Published, but I cannot access this data on the second page.

User Model

import Combine
struct User: Codable, Identifiable {
    
    var id = UUID()
    var name: String
    var surName: String
    
}

UserDataStore

import Combine
class UserDataStore: ObservableObject {

    @Published var users: [User] = []
    
}

ContentView

I get information from the user with TextField objects on the contentView screen. After pressing the button, I add it to the array in the UserDataStore. I redirect to the detail page.

struct ContentView: View {
    @State var name: String = ""
    @State var surName: String = ""
    @State var user = User(name: "", surName: "")
    @State var show: Bool = false
    
    @ObservedObject var userStore = UserDataStore()
    
    var body: some View {
        
        NavigationView {
            VStack(spacing: 50) {
                TextField("isim", text: $name)
                TextField("soyİsim", text: $surName)
                
                NavigationLink(
                    destination: DetailView(),
                    isActive: $show,
                    label: {
                        Button(action: {
                            self.user.name = name
                            self.user.surName = surName
                            self.userStore.users.append(user)
                            self.show = true
                            
                        }) {
                            Text("Kaydet")
                        }
                    })
            }
        }
    }
}

DetailView

On the detail page, I try to view the recorded information, but I cannot.

struct DetailView: View {
    @ObservedObject var user = UserDataStore()
    
    var body: some View {
        ForEach(user.users) { item in
            Text("\(item.name)")
        }
    }
}

Upvotes: 1

Views: 737

Answers (1)

the.blaggy
the.blaggy

Reputation: 885

Like @"New Dev" explained you're initializing a new instance of UserDataStore therefore your data isn't accessible from the DetailView.

You can use an EnvironmentObject to access the data from ContentView to DetailView.

In order to do this you would have to set the NavigationLinks destination to:

destination: DetailView().environmentObject(userStore)

Then you can access it from the DetailView like this:

@EnvironmentObject var user: UserDataStore

Upvotes: 1

Related Questions