Search code examples
iosswiftswiftui

Issues adding new items to model's string array and displaying them


I have a property in a model that Is initially empty as string array (userReports) that will hold the users' notes. But when I attempt to append values to it and display it, it nothing updates. Racking my brain understanding data persistence overall so im not sure if im going about this the right way.

@Model
final class ActiveStash {
    var substanceClass: String
    var substance: String
    var weight: UInt
    var substanceCost: UInt?
    var StashDescription: String?
    var date: Date
    var unit: String
    var dosages: Int?
    var userReports: [String]?

    init(substanceClass: String, substance: String, weight: UInt, substanceCost: UInt? = nil, StashDescription: String? = nil, date: Date, unit: String, dosages: Int? = nil, userReports: [String]? = nil) {
        self.substanceClass = substanceClass
        self.substance = substance
        self.weight = weight
        self.substanceCost = substanceCost
        self.StashDescription = StashDescription
        self.date = date
        self.unit = unit
        self.dosages = dosages
        self.userReports = userReports
    }
}

Function to add the users' report to the model

   func addReport() {
        guard !inputReport.isEmpty else {
            return
        }

        var updatedReports = stashed.userReports
        stashed.userReports = updatedReports

        updatedReports.append(inputReport)

        try? modelContext.save()

        dismiss()
    }

How I'm attempting to display the text after the function call from another page

struct StashLinkView: View {
    @Environment(\.modelContext) var modelContext
    let stashed: ActiveStash
    @State private var viewSelect = "Usage"
    var viewName = ["Usage", "Report"]
    let currencySymbol = Locale.current.currencySymbol ?? ""
    @State private var isSheetShown = false
    
    var body: some View {
        VStack {
           /// other code
        }

   // not sure im im doing this block  correctly

        VStack {
            if let userReports = stashed.userReports, !userReports.isEmpty {
                ForEach(userReports, id: \.self) { report in
                    VStack {
                        Text(report) 
                    }
                }
            } else {
                Text("No Notes")
            }
        }

Solution

  • func addReport() {
        guard !inputReport.isEmpty else {
            return
        }
         stashed.userReports.append(inputReport)
    
        try? modelContext.save()
    
        dismiss()
    }