Ask Your Question
4

How can I fill a list within a sub view, located inside a tab view, specifically with children data from a Firebase database node that corresponds to the currently logged in user?

asked 2022-12-22 11:00:00 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2021-11-14 20:00:00 +0000

djk gravatar image

Assuming you are using SwiftUI, you can follow these steps:

  1. Create a model for your data. This model should contain the properties of your child data and conform to Identifiable.

    struct Child: Identifiable {
       let id: String
       let name: String
       let age: Int
    }
    
  2. Create an ObservableObject that will hold your child data.

    class ChildViewModel: ObservableObject {
       @Published var children: [Child] = []
    
       init() {
           // Get the currently logged in user UID
           guard let uid = Auth.auth().currentUser?.uid else { return }
    
           // Set up a database reference to the children node for this user
           let ref = Database.database().reference().child("users").child(uid).child("children")
    
           // Listen for child added events and update the children array
           ref.observe(.childAdded) { snapshot in
               if let data = snapshot.value as? [String: Any] {
                   let id = snapshot.key
                   let name = data["name"] as? String ?? "Unknown"
                   let age = data["age"] as? Int ?? 0
                   self.children.append(Child(id: id, name: name, age: age))
               }
           }
       }
    }
    
  3. In your sub view, create an instance of the ChildViewModel and use a ForEach to display each child in a list.

    struct ChildListView: View {
       @ObservedObject var viewModel = ChildViewModel()
    
       var body: some View {
           List(viewModel.children) { child in
               Text(child.name)
           }
       }
    }
    
  4. Add the ChildListView to your tab view.

    struct MyTabView: View {
       var body: some View {
           TabView {
               ChildListView()
                   .tabItem {
                       Image(systemName: "person.crop.circle")
                       Text("Children")
                   }
           }
       }
    }
    

Make sure you have imported Firebase and FirebaseAuth in your code.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-12-22 11:00:00 +0000

Seen: 8 times

Last updated: Nov 14 '21