'Issue: SwiftUI Button in Toolbar does not respond with empty array in a ForEach loop

Issue: SwiftUI Button in Toolbar does not respond with empty array in a ForEach loop. (see attached code snippet)

The viewModel.fetchAllContainer() function in OnAppear() queries a DB and fills the viewModel.fmContainers array

When I start the app with an empty database, the plus.circle button in the toolbar does not respond. However, once a record is present in viewModel.fmContainers, the UI responds as expected.

....
    var body: some View {
        NavigationView {
            List {
                ForEach(viewModel.fmContainers, id: \.id) { fmContainer in
                    Button {
                        modal = .update_Container(fmContainer)
                    } label: {
                        FMContainerCellView(fmContainer: fmContainer)
                    }
                }
                .sheet(item: $modal) {
                    // Aufräumarbeiten z.B. nachladen
                    Task {
                        do {
                            try await viewModel.fetchAllContainer()
                        } catch {
                            print("ERROR: FMContainer not loaded")
                        }
                    }

                    
                } content: { modal in
                    switch modal {
                    case .add:
                        // new Container
                        FMContainerDetailView(viewModel: FMContainerDetailViewModel() )
                    case .update_Container(let fmContainer):
                        // update Container
                        FMContainerDetailView(viewModel: FMContainerDetailViewModel(isUpdating: true, fmContainer: fmContainer))
                    default:
                        Text("Error")
                    }
                }
            }
            .listStyle(PlainListStyle())
            .navigationTitle("Objektliste")
            .toolbar {
                ToolbarItem {
                    Image(systemName: "plus.circle")
                        .onTapGesture {
                            modal = .add
                        }
                }
            }
            .onAppear() {
                Task {
                    do {
                        try await viewModel.fetchAllContainer()
                     
                    } catch {
                        print("ERROR: FMContainer not loaded")
                    }
                }
            }

        }
    }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source