0

I am looking to preserve the viewModel.counter value even when valueComingFromParent value changes.

Right now, when Incrementer button is clicked it increments viewModel.counter value. But when Toast button is clicked, it changes value of a property in valueComingFromParent. and at the same time viewModel.counter value resets to 0

struct ChildView: View {

@ObservedObject var viewModel = ChildViewModel()
@EnvironmentObject var valueComingFromParent: SomeOtherViewModel

var body: some View {
        VStack {
                    Button("Toast", action: {
                        
                        valueComingFromParent.toast.toggle()
                    })
                    
                    Button("Incrementer \(viewModel.counter)", action: {
                        viewModel.counter += 1
                    })
                }
        }
}

Can anybody tell me how can I preserve the value of viewModel.counter even if valueComingFromParent value changes.

Thanks

Nabeel
  • 841
  • 1
  • 10
  • 23
  • 2
    Use StateObject instead of ObservedObject – jnpdx Nov 25 '22 at 17:25
  • these consistency problems are why we don't use view model objects in SwiftUI – malhal Nov 25 '22 at 23:50
  • what do you suggest as an alternative to view model approach? @malhal – Nabeel Nov 26 '22 at 01:59
  • The solution given by @jnpdx worked for above issue but I am still facing some other issues. For some reason the child view navigates back to parent view when Toast button is clicked. and Navigation height gets increased as well. strange issues. – Nabeel Nov 26 '22 at 02:55

0 Answers0