Home > Blockchain >  SwiftUI: View doesnt update when Data added to Realm DB through Sheet
SwiftUI: View doesnt update when Data added to Realm DB through Sheet

Time:08-03

I am having a very irritating problem, with my view and Realm DB. So I have a very simple code, I have a view were I display the stored Names in my Realm DataBase. These Names are stored by navigating to another view through a navigationlink.

In this view a name is written in a Textfield and stored to the DB. When I go back to my original View the name isnt being displayed, so I have to rerender my Simulator for it to update and display the recently added Name.

Any ideas on how to solve this issue?

This is my code:

This is my main view, where the names should be displayed:

class Name: Object, ObjectKeyIdentifiable {
    @Persisted(primaryKey: true) var id: ObjectId
    @Persisted var name = ""
}


struct playground: View {
    
    @StateObject var nameManager = NameManager()
    @State var myName = ""
    @State var showSheet = false
    
    
    var body: some View {
        NavigationView{
            VStack{
                NavigationLink(destination: dataView(myName: $myName)) {
                    Text("go to another view to write name ")
                }
                
                
                ForEach(nameManager.names, id: \.id) {name in
                    Text("\(name.name)")
                        .onTapGesture {
                            nameManager.deleteName(id: name.id)
                        }
                }
                
            }.sheet(isPresented: $showSheet) {
                dataView(myName: $myName)
            }
        }
    }
}

And this is the view im using to write the name and store it:

struct dataView: View {
    @Binding var myName : String
    @StateObject var nameManager = NameManager()
    
    
    var body: some View {
        
        VStack{
            TextField("Enter username...", text: $myName)
            
            
            Button("store to DB") {
                nameManager.addName(name: myName)
                myName = ""
                
                
            }
        }
        
    }
}

CodePudding user response:

You use different instances of NameManager, but should use one, like

}.sheet(isPresented: $showSheet) {
    dataView(nameManager: nameManager, myName: $myName) // inject !!

and

struct dataView: View {
    @Binding var myName : String
    @ObservedObject var nameManager: NameManager   // << external !!

// ...
  • Related