I have a SwiftUI View that I am presenting in a UIViewController container. When a user creates a post I want the feed to fetch that new post from the service and insert it at the beginning of the array. All of that is working (the service fetches the correct post), but the issue is the SwiftUI view does not update to reflect the insertion of that new post. If I scroll down and then back up the feed will have a duplicate post of the last post before the newest one.
Any ideas why this may be happening?
I've tried removing Lazy from the VStack but that didn't help, I'm not sure why the Published posts array wouldn't update the view
The SwiftUI View:
var contentView: some View {
ScrollViewReader { scrollViewProxy in
ScrollView {
LazyVStack(alignment: .center, spacing: 6) {
ForEach(viewModel.posts.indices, id: \.self) { index in
// Business Logic
}
}
}
}
}
func reloadWithPost() {
Task {
await viewModel.loadNew()
}
}
In View Model
@Published var posts: [PostOBJ] = []
@MainActor
func loadNew() async {
self.loadingNew = true
do {
let posts = try await service.getPageZero()
let newPosts: [PostOBJ]? = posts.filter { post in
!self.posts.contains { $0.id == post.id }
}
guard let newPosts: [PostOBJ] = newPosts, !newPosts.isEmpty else {
return
}
let allPosts: [PostOBJ] = newPosts + self.posts
self.posts = allPosts
} catch { }
}
In UIKit UIViewController Container
var feedView: FeedView?
override func viewDidLoad() {
super.viewDidLoad()
let view = FeedView(openDelegate: self)
self.feedView = view
let controller: UIViewController = UIHostingController(rootView: view)
presentedVC = controller
}
extension ViewControllersContainer: ComposePostDelegate {
func postComposed() {
self.feedView?.reloadWithPost()
}
}