I am having trouble with using static on a function in my post repository its saying “Static methods may only be declared on a type Remove 'static '”. Also having trouble with the post view model when I use dot annotation fetchPosts() on PostsRepository it says “Type ‘PostsRepository’ has no member ‘fetchPosts’”. I have tried linking the two repository and view model together but wasn’t successful. Is this the solution for the type PostsRepository has no member fetchPosts? I don’t know about the static problem though. Kinda lost.
Post View Model Code
import Foundation
@MainActor
class PostsViewModel: ObservableObject {
@Published var posts = [Post]()
func makeCreateAction() -> NewPostForm.CreateAction {
return { [weak self] post in
try await PostsRepository.create(post)
self?.posts.insert(post, at: 0)
}
}
func fetchPosts() {
Task {
do {
posts = try await PostsRepository.fetchPosts()
} catch {
print("[PostsViewModel] Cannot fetch posts: \(error)")
}
}
}
}
PostRepository Code
import Foundation
import FirebaseFirestore
import FirebaseFirestoreSwift
let postsReference = Firestore.firestore().collection("posts")
static func fetchPosts() async throws -> [Post] {
let snapshot = try await postsReference.order(by: "timestamp", descending: true).getDocuments()
return snapshot.documents.compactMap { document in
try! document.data(as: Post.self)
}
}
struct PostsRepository {
static let postsReference = Firestore.firestore().collection("posts")
static func create(_ post: Post) async throws {
let document = postsReference.document(post.id.uuidString)
try await document.setData(from: post)
}
}
private extension DocumentReference {
func setData<T: Encodable>(from value: T) async throws {
return try await withCheckedThrowingContinuation { continuation in
// Method only throws if there's an encoding error, which indicates a problem with our model
// We handled this with a force try, while all other errors are passed to the completion handler
try! setData(from: value) { error in
if let error = error {
continuation.resume(throwing: error)
return
}
continuation.resume()
}
}
}
}