'Toolbar Item is not updating after items are deleted from core data in SwiftUI
I have a problem. I have a view which contains a toolbar item, a "Shopping Cart - displays how many items are in the cart". I have a screen which contains a button, and after the button is pressed, all the items from the entinty "LocalName" are deleted, so basically there is no item left there, but the "Shopping Cart number of items " is not updating. Is updating only after the application is terminated and opened again.
I will share my code below :
struct OrderCompletedVieww: View {
@StateObject var coreDataViewModel = CoreDataViewModel()
@Environment(\.managedObjectContext) private var viewContext
@FetchRequest(sortDescriptors: [])
private var menus : FetchedResults<LocalMenu>
var body: some View {
VStack {
Button {
let fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "LocalMenu")
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
do {
try
coreDataViewModel.manager.context.execute(deleteRequest)
} catch let error as NSError {
}
coreDataViewModel.saveContext()
} label: {
Text("Delete menus")
}
.padding()
}
}
}
struct MainVieww: View {
@EnvironmentObject var syncViewModel : SyncViewModel
@Environment(\.managedObjectContext) private var viewContext
@FetchRequest(sortDescriptors: [])
private var menus : FetchedResults<LocalMenu>
var body: some View {
NavigationView{
MeniuriView()
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
ToolbarButtons(numberOfProducts: menus.count)
}
}
}
}
}
struct ToolbarButtons: View {
@Environment(\.managedObjectContext) private var viewContext
@FetchRequest(sortDescriptors: [])
@State var pushActive : Bool = false
var numberOfProducts : Int
var body: some View {
ZStack {
Spacer()
NavigationLink(destination: CartView()
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
Text("Cos")
.font(.system(size: 24))
.bold()
}
}
, label: {
ZStack(alignment: .topTrailing) {
Image("cartIcon")
.padding(.top, 5)
if numberOfProducts > 0 {
Text("\(numberOfProducts)")
.font(.caption2).bold()
.foregroundColor(.white)
.frame(width: 15, height: 15)
.background(Color.tabItemColor)
.cornerRadius(50)
.offset(x: 10, y: -8)
}
}
}
)
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
