UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SwiftUI dismiss and save model at the same time

Forums > SwiftUI

Hi,

I used this post to dismiss my SwiftUI view and I used this post to try and get this warning away, that I am modifying the state during a view update.

I am unsure how to do that:

I have a DetailView which takes a Binding<[BonusModel]>. In the detail view I fill in a form and on save, I do bonuses.wrappedValue.append(BonusModel(...)) which adds a bonus to the list of bonuses.

This list is used in MainView as a state, so in this view I am listing all the bonuses. When hitting save on the DetailView, a bonus is added and the bonuses list in the main view is updated. I then want to dismiss the detail view using the first posts' method:

presentationMode.wrappedValue.dismiss()
bonuses.wrappedValue.append(BonusModel())

This creates the warning that I am trying to avoid: [SwiftUI] Modifying state during view update, this will cause undefined behavior.

Any idea how I can solve this particular case? Thank you very much.

2      

Did you try to dismiss the dialog asynchronously after the model has been updated? This would allow the model to update the view and only after that, you are dismissing the current view.

bonuses.wrappedValue.append(BonusModel())
DispatchQueue.main.async {
    presentationMode.wrappedValue.dismiss()
}

2      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.