I have a SwiftUI List which I want to update once any field of the TransactionEntity
record is updated. Here is the code:
struct HomeListView: View {
var categoryName: String
@State private var transactions: [TransactionEntity] = []
var body: some View {
List {
Section(
header: HStack {
Text(categoryModel.name)
},
content: {
ForEach(transactions) { transaction in
let vm = RecordViewModel(transaction: transaction)
NavigationLink(
destination: RecordDetailsView(viewModel: vm),
label: {
HStack {
Text(transaction.categoryName)
Text(transaction.amount)
}
})
}
}
)
}
.onAppear(perform: {
transactions = viewModel.fetchTransactions(cat: categoryName)
})
}
The RecordDetailsView
page as follows:
struct RecordDetailsView: View {
@Environment(.presentationMode) var presentation
@State var viewModel: RecordViewModel
@State private var isAlertPresented = false
var body: some View {
let amountField = TextField("", text: self.$viewModel.amountValue)
.keyboardType(.decimalPad)
let saveButton = Button(
action: {
self.saveAction()
},
label: {
Text("Save")
}
)
Form {
Section(header:
HStack {
Image(systemName: "dollarsign")
Text("Amount")
}) {
amountField
}
Section(header:
HStack {
Image(systemName: "calendar")
Text("Date")
}) {
DatePicker(
selection: $viewModel.valueDate,
in: ...Date(),
displayedComponents: [ .date, .hourAndMinute],
label: {
Text("")
})
.datePickerStyle(.wheel)
}
}
}
func saveAction() {
viewModel.saveTransactions(amount: viewModel.amountValue, transactionDate: viewModel.valueDate)
self.presentation.wrappedValue.dismiss()
}
}
Now the problem is after I modify the amount or date and go back to listing page the list doesn’t update with latest amount or date of that particular record. Even onAppear
I’m refreshing the transactions
array.
So how to I force update the Section inside List View. Thanks in advance.