I'm trying to populate a group of views using ForEach. I've used Alamofire for fetching the data and setting the @State property to trigger an update. Unfortunately, the updates only show up when I switch screens(Using a TabBar) or go to the home screen and re-open the app.
Following is the code snippet that I've used:
@State var posts : [Post]
    
    var body: some View {
        ScrollView{
            VStack(alignment: .leading, spacing: 0){
                ForEach(posts, id: \.id) { preview in
                    PreviewDetailView(preview: preview).background(Color(.white).cornerRadius(30))
                }
            }
        }.onAppear(perform: {fetchPosts()})
    }
Apparently, the PreviewDetailView(in which I'm displaying the API response data) gets triggered but the view doesn't update.
The reason is when you use stack or ForEach within ScrollView, you have to setFrame limits to initialize the view Setting like the following. 
ScrollView{
    VStack(alignment: .leading, spacing: 0){        
        ForEach(self.posts, id: \.id) { preview in
           PreviewDetailView(preview: preview)
               .background(Color(.red).cornerRadius(30))
        }.frame(maxWidth: .infinity) // Here
    }
}.onAppear{
    self.fetchPosts()   
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With