Home > Back-end >  @EnvironmentObject property not working properly in swiftUI
@EnvironmentObject property not working properly in swiftUI

Time:10-19

DataStorage.swift 

class DataStorage: ObservableObject {
    @Published var cartArray = [Order]()
}

ViewModel.swift
 
class ViewModel : ObservableObject{
     var dataStorage = DataStorage()
     @Published var bookOptionsArray = [BookOption]()

  func addBook (bookId:String ,bookName : String){
       dataStorage.cartArray.append(Order(bookId:bookId, bookName: bookName, bookoptions:self.bookOptionsArray))
}



View1:

struct View1: View {
    @ObservedObject var vwModel = ViewModel()
    @EnvironmentObject var datastrg: DataStorage
    ListView(vwModel:vwModel)
}

 struct ListView: View{
     @ObservedObject var vwModel = ViewModel()
     @EnvironmentObject var dt: DataStorage 
        List(vwModel.bookoptions.bookList) {opn in

         //Display List
         //If a book a selected it will add to bookOptionsArray of viewModel. Call addBook() in ViewModel class
}

}


View3 

struct View3: View {
    @EnvironmentObject var dt : DataStorage
     List(dt.cartArray){item in
    //Display the selected books to place order
}

View3 displays empty List ,because cartArray is not stored properly How to display List in View3 ? Any ideas/ suggestions will be helpful

CodePudding user response:

You are not calling your function addBook anywhere, add an onappear to your view3 calling the function and your list will populate with data.

CodePudding user response:

You are creating a local DataStorage in your view model instead of using the one in the @EnvironmentObject so instead inject it into the view model.

First change the view model so you must inject DataStorage

class ViewModel: ObservableObject {
    var dataStorage: DataStorage
    //...

    init(dataStorage: DataStorage) {
        self.dataStorage = dataStorage
    }
    //...
}

Then change View1 so you create the view model in an init

struct View1: View {
    @ObservedObject var vwModel: ViewModel
    @EnvironmentObject var datastrg: DataStorage

    init() {
        vwModel = ViewModel(dataStorage: datastrg)
    }
    //...
}
  • Related