Initializing a @StateObject from an @EnvironmentObject

I have an @EnvironmentObject, store, that has a variable I need to pass the variable as a parameter to my @StateObject, vm, initializer. I first tried the init but an @EnvironmentObject is not yet existing upon View init. So then I tried the onAppear but onAppear does not allow use of self. Is this even possible? For reference I've included both the init and the onAppear, neither works.

struct NewsView: View {
@EnvironmentObject var store: Store
@StateObject private var vm: NewsViewModel

init() {
    self._vm = StateObject(wrappedValue: NewsViewModel(self._store.wrappedValue.newsApi))
var body: some View {
    if == true {
        HStack {
                .aspectRatio(contentMode: .fit)
                .frame(width: 20)
            Text( ?? "")
            Button {
       = false
            } label: {
                Image(systemName: "xmark")
                    .frame(width: 12)
        .onChange(of: { newStore in
            self._vm = StateObject(wrappedValue: NewsViewModel(newStore.newsApi))


Question specific to SwiftUI, which is Apple's specific framework, is off-topic for this forum. I'd suggest that you ask this kind of questions over instead. You're more likely to get a help there.

Terms of Service

Privacy Policy

Cookie Policy