Search code examples
mvvmswiftuicombine

SwiftUI Binding to parent view re-renders child view


I have a child view that is given a binding from the parent view, which controls the app's sidebar menu. When I click the button to toggle showSidebar and open the menu, my vm is re-created because the view is re-rendered? Is there a way to do this without affecting the view model?

struct OnboardingView: View {
    @Environment (\.presentationMode) var presentationMode
    @ObservedObject private var vm: OnboardingViewModel
    @State private var filtering = false
    @Binding var showSidebar: Bool

init(showSidebar: Binding<Bool>) {
    self._showSidebar = showSidebar
    self.vm = OnboardingViewModel()
}

Solution

  • Give this a try...

    Change this

    @ObservedObject private var vm: OnboardingViewModel
    

    to

    @StateObject private var vm: OnboardingViewModel = OnboardingViewModel()
    

    and get rid of

    init(showSidebar: Binding<Bool>) {
        self._showSidebar = showSidebar
        self.vm = OnboardingViewModel()
    }
    

    it’s unsafe to create an observed object inside a view without an @StateObject

    https://developer.apple.com/documentation/swiftui/managing-model-data-in-your-app