2

In my app the first tab in the starting screen does not show any data. The code for the tab is as follows:

import SwiftUI
import FirebaseFirestore
import Firebase
import FirebaseFirestoreSwift

struct LibraryScreen: View {
    @ObservedObject var viewModel = BookViewModel()
    
    
    var body: some View {
        VStack
            {
                List(viewModel.books){book in
                    Text(book.name)
                }
            }.onAppear(){
                self.viewModel.fetchData()
                print("Fetching books")
            }
        .navigationBarTitle("Library", displayMode: .inline)
    }
}

struct LibraryScreen_Previews: PreviewProvider {
    static var previews: some View {
        LibraryScreen()
    }
}

However when navigating back from another tab the data shows up as intended. Is there something I should be using instead of .onappear?

EDIT: Just to clarify I want to have the data from viewModel.fetchData display on startup without having to implement a button but although the print statement shows up in the console the fetched data doesn't.

HamdyAli
  • 173
  • 3
  • 14

1 Answers1

0

Try this.

List {
    if !viewModel.books.isEmpty {
        ForEach(viewModel.books) { book in {
            Text(book.name)
        }
    }
}
M1X
  • 4,971
  • 10
  • 61
  • 123