List not updated after adding a new item

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

Show the code for the view where you add the new item and the code that adds the new item.

Without that code people can only guess as to why the list is not updating when you add a new item.

I add item from this view :

struct InvoiceView: View {

    @StateObject var itemsData = ItemsData()

    @AppStorage("storeName") private var storeName = ""

    @AppStorage("invoiceNumber") private var invoiceNumber = ""

    @AppStorage("contactNumber") private var contactNumber = ""

    @State private var invoiceDate = Date()

    @AppStorage("customerName") private var customerName = ""

    @AppStorage("customerAddress") private var customerAddress = ""

    @AppStorage("cusContactNumber") private var cusContactNumber = ""

    @State private var showingAddItem = false

    @State private var showingHistoryView = false

    // FOR CALCULATE TOTAL AMOUNT.
    private var totalAmount: Double {
        itemsData.items.reduce(0.0) { partialResult, item in
            partialResult + item.price
            // also can be expressed as { $0 + $1.amount }
        }
    }

    // FOR CALCULATE DISCOUNT AMOUNT. (READING FROM AddView)
    private var discountAmount: Double {
        itemsData.items.reduce(0.0) { partialResult, item in
            partialResult + item.discountAmount
            // also can be expressed as { $0 + $1.amount }
        }
    }

    // FOR CALCULATE VAT AMOUNT.
    private var vatAmount1: Double {
        itemsData.items.reduce(0.0) { partialResult, item in
            if item.vat > 0 {
                let netAmount = item.price / (1 + item.vat/100)
                let vatamount = item.price - netAmount
                return partialResult + vatamount
            }
            return partialResult
        }
    }

    @State private var paymentM = "Cash"

    let paymentsList = ["Cash", "BenefitPay", "Debit Card"]

    @ObservedObject var historyData: historyData

    @State private var type = "Income"

    @ObservedObject var expenses: Expenses

    var body: some View {
        NavigationView {
            List {
               
                Section(header: Text("Store Details")) {
                    TextField("Store Name", text: $storeName)

                    TextField("Invoice number", text: $invoiceNumber)

                    TextField("contact number", text: $contactNumber)
                }

                Section{
                    DatePicker("Date", selection: $invoiceDate)
                }

                Section(header: Text("Customer Details")) {

                    TextField("Customer Name", text: $customerName)

                    TextField("Customer Address", text: $customerAddress)

                    TextField("contact number", text: $cusContactNumber)

                }
                Group {
                    
                        Button{
                            showingAddItem = true
                        } label: {
                            HStack {
                                Image(systemName: "plus")
                                Text("Add Item")
                            }

                        }
                        .sheet(isPresented: $showingAddItem) {
                            AddView(ItemsData: itemsData)
                        }


                    ForEach(itemsData.items, id: \.id) { item in
                        HStack {
                            VStack(alignment: .leading) {

                                Text(item.name)
                                    .lineLimit(3)

                                Text("x\(item.quantity.formatted())")
                                    .foregroundColor(Color("grayed"))
                            }
                            Spacer()

                            VStack {
                                Text(item.price, format: .currency(code: Locale.current.currency?.identifier ?? "BD"))
                                    .lineLimit(3)
                            }
                        }
                    }
                    .onDelete(perform: removeItem)
                }

                HStack {
                    Text("Discount amount")
                    Spacer()
                    Text("\(discountAmount.formatted(.currency(code: Locale.current.currency?.identifier ?? "BD")))")
                        .foregroundColor(.blue)
                }

                HStack {
                    Text("VAT amount")
                    Spacer()
                    Text("\(vatAmount1.formatted(.currency(code: Locale.current.currency?.identifier ?? "BD")))")
                        .foregroundColor(.red)
                }

                HStack {
                    VStack(alignment: .leading) {
                        Text("Total")

                        Text(vatAmount1 > 0 ? "inc. VAT" : "")
                            .foregroundColor(Color("grayed"))

                    }
                    Spacer()
                    Text("\(totalAmount.formatted(.currency(code: Locale.current.currency?.identifier ?? "BD")))")
                        .foregroundColor(.green)
                }

                Group {
                    Section {
                        Picker("payment method", selection: $paymentM) {
                            ForEach(paymentsList, id: \.self) {
                                Text($0)
                            }
                        }
                    }
                }

            }
            .navigationTitle("Invoice Maker")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItemGroup {
                    ShareLink("Export PDF", item: render())
                        Button("Save") {

                            let income = ExpenseItem(name: customerName, type: type, amount: totalAmount - vatAmount1, date: invoiceDate, vat: vatAmount1)

                            expenses.items.insert(income, at: 0)

                            let item = HistoryData(storN: storeName, storNum: contactNumber, invNum: invoiceNumber, dat: invoiceDate, cus: customerName, cusAddr: customerAddress, cusNum: cusContactNumber, price: totalAmount)

                            historyData.item.insert(item, at: 0)

                        }
                    }

You have posted a lot of code, but there is one important piece of code missing. Your HistoryView has the following property that contains the history data:

@StateObject var historyData1 = historyData()

Your InvoiceView has the following property:

@ObservedObject var historyData: historyData

But I do not see any code on how you set the InvoiceView's historyData value. Is the value of historyData supposed to be the same as HistoryView's historyData1 property?

I think you have a better chance of getting an answer if you post a new question and strip out most of the code. The problem you have is the list isn't updating when you add a new item to it. Show the code that deals with adding the items to the list and strip out the other stuff. You have posted so much code that has nothing to do with the problem, and that makes it hard for people reading the question to see the code they need to answer your question.

I also recommend coming up with better names for some of your data structures and variables. You have a struct named HistoryData and a class named historyData. That is confusing because the only difference in the names is making the H in History uppercase or lowercase. You have a variable named historyData and another one named historyData1. I know it can be hard to come up with good variable names, but your code will be easier for people to read if you give your data structures and variables less confusing names.

List not updated after adding a new item
 
 
Q