'SwiftUI deleting object from list

I have a list of ingredients that is stored in a Sqlite DB and displayed in a list. Users can view an ingredient and edit/delete them. The changes are made in the DB but when returning to the original view the edits are not shown and if an ingredient is deleted and index out of range error occurs

Initial View:

@State var ingredients: [Ingredient] = []
var body: some View {
        List{
            ForEach(self.$ingredients){ ingredientModel in
                //print each ingredient
                IngredientListItem(ingredient: ingredientModel)
                    .listRowSeparator(.hidden)
            }
        }
        .onAppear(perform: {
            print("Load ingredients from DB")
            self.ingredients = Ingredient_DB().getIngredients()
        })
}

Ingredient row:

struct IngredientListItem: View {
    @Binding var ingredient: Ingredient
    @State var ingredientSelected: Bool = false
    
    var body: some View {
        NavigationLink (destination: ViewIngredientView(ingredient: $ingredient), isActive: self.$ingredientSelected){
            EmptyView()
        }
        HStack {
            if !ingredient.inStock{Image(systemName: "x.square")}
            Text(ingredient.name)
        }
    }
}

view ingredient:

struct ViewIngredientView: View {
    @Binding var ingredient: Ingredient
    @State var inStock: Bool = false
    @Environment(\.presentationMode) var mode: Binding<PresentationMode>

    var body: some View {
        VStack {
            Text(ingredient.name)
            Text(inStock ? "In Stock" : "Out Of Stock")
            Toggle("", isOn: self.$inStock)
            .onChange(of: inStock, perform: { value in
                //call DB to update ingredient with new values
                ingredient.inStock = inStock
                Ingredient_DB().updateIngredient(idValue: self.ingredient.id.uuidString, nameValue: ingredient.name, inStockValue: ingredient.inStock)
            })
        }
        .onAppear(perform: {
            //populate on screen
            self.inStock = ingredient.inStock
        })
        .navigationBarItems(trailing:
            Button("Delete") {
Ingredient_DB().deleteIngredient(ingredientID: ingredient.id.uuidString)
            }
    }
}

when the "inStock" value is changed the value is changed in the database but is not reflected on screen in the list. I can tell the value is changing in the database but the new values are not loaded into the list, the same list of ingredients in displayed.



Sources

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

Source: Stack Overflow

Solution Source