JamesSedlacek / Routing

SwiftUI library for abstracting navigation logic from views
MIT License
353 stars 19 forks source link

Why My Initialization is always calling ? #37

Closed zardasht-jazaa closed 4 months ago

zardasht-jazaa commented 7 months ago

` @ AppStorage(AppStorageKeys.localIdentifier.rawValue) var localIdentifier = "en" @ ObservedObject var newsViewModel: NewsViewModel let category: String let language: String

init(category: String,
     newsViewModel: NewsViewModel,
     language: String) {
    self.category = category
    self.language = language
    self.newsViewModel = newsViewModel
    newsViewModel.getNews(pagination: true,category: category)
}

`

inside the getNews function I have an print statement when ever the api request called, so the print state meant Is calling infinitely , what is the reason for that ?

this is how I came to that View

enum RouteTree: Routable { case .sectionView(let category, let newsViewModel, let language): SectionView(category: category, newsViewModel: newsViewModel, language: language) .navigationBarBackButtonHidden(true)

Screenshot 2024-04-01 at 1 20 33 AM

JamesSedlacek commented 4 months ago

You shouldn't call a function inside of an initializer. I'd recommend calling it inside of onAppear or task if it's an async function. I also don't think it makes sense to pass a ViewModel via the initializer. You can inject an observable object into the View's environment.