Hi everyone, List not updated after adding a new item from other view.
struct HistoryIView: View {
@StateObject var historyData1 = historyData()
private var totalAmount: Double {
historyData1.item.reduce(0.0) { partialResult, item in
partialResult + item.price
// also can be expressed as { $0 + $1.amount }
}
}
var body: some View {
NavigationView {
List {
Section(header: Text("Invoice History \(totalAmount.formatted(.currency(code: Locale.current.currency?.identifier ?? "BD")))")) {
ForEach(historyData1.item, id: \.id) { it in
HStack {
VStack(alignment: .leading) {
Text(it.cus)
Text(it.cusNum)
Text(it.dat.formatted(date: .abbreviated, time: .shortened))
.foregroundColor(Color("grayed"))
}
Spacer()
VStack {
HStack {
Text("Recipt#:")
.foregroundColor(.red)
Text("\(it.invNum)")
}
Text(it.price, format: .currency(code: Locale.current.currency?.identifier ?? "BD"))
.foregroundColor(.green)
}
}
}
.onDelete(perform: removeItem)
}
}
.navigationTitle("Invoice history")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
Button("Delete All") {
historyData1.item.removeAll()
}
.tint(.red)
}
}
}
}
func removeItem(at offsets: IndexSet) {
itemsData.items.remove(atOffsets: offsets)
}
}
the model :
struct HistoryData: Identifiable, Codable {
var id = UUID()
let storN: String
let storNum: String
let invNum: String
let dat: Date
let cus: String
let cusAddr: String
let cusNum: String
let price: Double
}
class historyData: ObservableObject {
@Published var item: [HistoryData] = [] {
// FOR STORE DATA IN THE UserDefaults.
didSet {
let encoder = JSONEncoder()
if let encode = try? encoder.encode(item) {
UserDefaults.standard.set(encode, forKey: "HistoryData")
}
}
}
// FOR LOAD DATA FROM UserDefaults.
init() {
if let savedItems = UserDefaults.standard.data(forKey: "HistoryData") {
if let decodedItems = try? JSONDecoder().decode([HistoryData].self, from: savedItems) {
item = decodedItems
return
}
}
item = []
}
}
How to fix this issue?
Thanks in advance