firebasegoogle-cloud-firestoreswiftuiproperty-wrapper

How to initialize the new Firebase @FirestoreQuery property wrapper with variables?


I use the new @FirestoreQuery property wrapper and it's working with the code below. But i need to use it/initialize it with variables, how can i do it (see below what I am trying to do)?

import SwiftUI
import FirebaseFirestoreSwift

struct TestFirestoreQuery: View {
    @State var itemLimit: Int = 5
    let increment: Int = 5
    
    @FirestoreQuery(collectionPath: "/discussions/blablabal/messages",
                    predicates: [
                        .order(by: "dateCreated", descending: true),
                        .limit(to: 5)
                    ]
    ) fileprivate var MessageResults: Result<[Message_M], Error>
    
    var body: some View {
        VStack {
            if case let .success(Messages) = MessageResults {
                List(Messages.reversed()) { message in
                    Text("\(message.msg)")
                }
                .refreshable{
                    itemLimit += increment
                    $MessageResults.predicates = [
                        .order(by: "dateCreated", descending: true),
                        .limit(to: itemLimit)
                    ]
                }
            }
            else if case let .failure(error) = MessageResults {
                // Handle error
                Text("Couldn't map data: \(error.localizedDescription)")
            }
            Button {
                itemLimit += increment
                $MessageResults.predicates = [
                    .order(by: "dateCreated", descending: true),
                    .limit(to: itemLimit)
                ]
            } label: {
                Text("Tap me!")
                    .padding()
                    .foregroundColor(.white)
                    .background(.red)
            }
        }
    }
}

what I want to do but it doesn't work :

...
    @State var itemLimit: Int = 5
    let increment: Int = 5
    let path: String = "/discussions/blablabal/messages"
    
    @FirestoreQuery(collectionPath: path,
                    predicates: [
                        .order(by: "dateCreated", descending: true),
                        .limit(to: itemLimit)
                    ]
    ) fileprivate var MessageResults: Result<[Message_M], Error>

...

I got these errors :


Solution

  • Ok you can initialize them in the onAppear :

    .onAppear {
               $MessageResults.path = path
    
               $MessageResults.predicates = [
                              .order(by: "dateCreated", descending: true),
                              .limit(to: itemLimit)
                              ]
    
    }