I am trying to learn Swift, and swiftUI.
I have a class : ObservableObject called within a button.
the class fetches some data, and stores it in a data var (an array of (string:any))
the class function fetch data is called within onAppear function in the main view VStack. the results of the function populates a list.
it all works fine, but each time I recall the view, the list empties itself.
here s the class opening
class fetchDataModel: ObservableObject {
@Published var datas:[data] = [data]()
now the datalist view :
struct allData: View {
@ObservedObject var datas = fetchDataModel()
var body: some View {
VStack{
NavigationView {
List(datas.data){ data in
NavigationLink(destination: data(data: data)){
HStack{
Text(data.someText)
}
}
}
}
}.navigationBarTitle(Text("Landmarks"))
.onAppear(){
self.datas.fetchData()
}
}
}
I have a side menu that populates a motherView, once a button from the side menu is clicked, it calls datalist() (session is an environmentalObject)
if session.currentPage == "data" {
myview = AnyView(allDatas())
}
So I guess, each time I set myView to allDatas, it reinitialises the datas = fetchDataModel() class, and sets all its values to 0. Is there a way to avoid this problem ?