SwiftUI Read Data from Firebase to View and Function

Viewed 119

I'm still a beginner and have a question, I'm trying to read data from the database with Firebase how can I pass this to a text? I want to pass "testUser" and display it.

anyone have an idea :-)

import SwiftUI
import FirebaseDatabase
import Firebase

struct uebergeben: View {

    var body: some View {

        VStack {

            Text(datenLesen)

        }
    }

    func datenLesen() {
        let user = Auth.auth().currentUser!.uid

        Database.database().reference().child("benutzer").child(user).child("nuterinfo").child("nutzername").observeSingleEvent(of: .value, with: { (snapshot) in
            if let testUser = snapshot.value as? String {
                print(testUser)
            }

        })
    }
}

struct uebergeben_Previews: PreviewProvider {
    static var previews: some View {
        uebergeben(test: "Daten Abrufen")
    }
}
1 Answers

You can use the @State properties inside of your view. For more details about @State you can read in the documentation. In short, the @State property is a property that is responsible for the state of the view. When the value of this property changes it means that the state of the views also changes and our view redraws itself.

struct uebergeben: View {
    @State
    private var user: String = "" // Declare the view's state property
    
    var body: some View {
        VStack {
            Text(user)
        }
        .onAppear {
            datenLesen() // Call the method for the fetching data
        }
    }

    func datenLesen() {
        let user = Auth.auth().currentUser!.uid

        Database.database().reference().child("benutzer").child(user).child("nuterinfo").child("nutzername").observeSingleEvent(of: .value, with: { (snapshot) in
            if let testUser = snapshot.value as? String {
                self.user = user // Change the value of the state property of the view
            }

        })
    }
}

Feel free if want to ask something additional about this or you have some questions for code

Related