I'm trying to build a social media application that shows a list of posts displayed in the PostGridView.
PostView is the design of each post in the grid/feed.
My code currently doesn't display anything in the application. I can't seem to figure out why. The database also has sample data that matches the model. Any help would be appreciated. Thank you!
Post:
import Foundation
import FirebaseFirestoreSwift
struct Post: Identifiable, Codable, Hashable {
@DocumentID var id: String? = UUID().uuidString
var createdBy: String
var createdOn: String
var statement: String
var agreeCount: Int = 0
var disagreeCount: Int = 0
enum CodingKeys: String, CodingKey {
case id
case createdBy
case createdOn
case statement
case agreeCount
case disagreeCount
}
}
PostViewModel:
import Foundation
import Firebase
import FirebaseFirestoreSwift
import FirebaseFirestore
class PostViewModel: ObservableObject {
@Published var posts = [Post]()
private var db = Firestore.firestore()
func fetchPostData() {
db.collection("posts").addSnapshotListener { (querySnapshot, error) in
guard let documents = querySnapshot?.documents else {
print("No posts")
return
}
self.posts = documents.compactMap { queryDocumentSnapshot -> Post? in
return try? queryDocumentSnapshot.data(as: Post.self)
}
}
}
func addPost(_ post: Post) {
do {
let _ = try db.collection("posts").addDocument(from: post)
}
catch {
print(error)
}
}
}
PostGridView:
import SwiftUI
import Foundation
import Firebase
import FirebaseFirestoreSwift
struct PostGridView: View {
@ObservedObject var viewModel = PostViewModel()
var body: some View {
TabView {
NavigationView {
LazyVStack {
ForEach(viewModel.posts, id: \.self) { Post in
PostView(post: Post)
}
}
.onAppear() {
self.viewModel.fetchPostData()
}
}
}
}
}
PostView:
import SwiftUI
struct PostView: View {
@State var post: Post
var body: some View {
VStack(alignment: .center, spacing: 0) {
Text(post.statement)
.font(.headline)
.fontWeight(.bold)
.padding()
}
}
}