Jacob Agee
Jacob Agee

Reputation: 23

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()
}

Upvotes: 1

Views: 889

Answers (1)

lorem ipsum
lorem ipsum

Reputation: 29242

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

Upvotes: 1

Related Questions