Update views on ForEach using StateObject - SwiftUI

Sep 23, 2022 1 min read
Update views on ForEach using StateObject - SwiftUI

One of the beautiful things about SwiftUI is its useful managed state, by using an environment we can have live access to any of its objects, however sometimes while using a ForEach the changes are not reflected, let's see why.

If you simply do:

@EnvironmentObject var myState: MyState

ForEach(myState.userWallets) { wallet in
    MyView(wallet: wallet)
}

you will get a positive result, however there is a hidden "bug", in order to see the changes reflected on MyView and sub-views once such model in the environment changes, you need to apply the binding property otherwise you'll have to do tricky things such as .onAppear, .onChange, etc... which are not necessary. Let SwiftUI understand this is a model that you care about its live content, by binding it, so the ForEach looks like: ForEach($myState.userWallets) { wallet in

Of course you don't need to bind all the way the rabbit hole, but it's good to know why this happens :)

Simple but tricky... for mre info look at the docs.

Great! Next, complete checkout for full access to ArturoFM.
Welcome back! You've successfully signed in.
You've successfully subscribed to ArturoFM.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info has been updated.
Your billing was not updated.