Reputation: 3
I have a simple application that has a date component that gets saved to core data. I've set up a view to allow for editing, but when this edit view loads, my date picker always shows the current date, not the date previously entered when the item was created.
I tried using onAppear() to set the date value, and this does work. I load the edit view and the DatePicker shows the stored date as I would like it to. However, if I wish to make a change to the picker, Xcode throws an alert stating "Modifying state during view update, this will cause undefined behavior." I'm not sure how I set this value and not cause and issue with state.
var thisCook: CookData
@State var updatedDate = Date()
DatePicker(selection: $updatedDate) {
Text("Cook Date:")
}.onAppear() {
self.updatedDate = self.thisCook.date
//Alert is shown for the line above
}
I'm not sure exactly what code will be helpful here, but this is where my issue arrises. If I need to show more, let me know. As I said before, this does load the edit view with the previously saved date, but if I wish to enter that date, I get the modifying state alert.
Upvotes: 0
Views: 293
Reputation: 5358
You are assigning the current date with @State var updatedDate = Date()
, that's why it shows that. Inside init you can also assign theCook.date
to _updatedDate
.
To avoid Modifying state during view update
it possibly helps to move the state into an ObservableObject
.
Upvotes: 0