Emre Gemici
Emre Gemici

Reputation: 67

“ 'Task' has no accessible initializers” issue for SwiftUI

How can I use:

struct TestView: View {
    @StateObject private var housesListVM = HousesListViewModel()
    var body: some View {
        Text("Hello, World!")
            .onAppear {
                Task {
                    await housesListVM.fetchAll()
                }
            }
    }
}

enter image description here

Function:

@MainActor
func fetchAll() async {
    self.networking = true

    let params: Parameters = ["Page": 1,
                              "Take": 100,
                              "NeedTotalCount": false,
                              "SortBy": "",
                              "SortAscending": true,
                              "FirstHomeId": "\(self.selectedFirstHome)"]

    let endpoint = HouseEndpoint.paginate(params: params)

    do {
        
        let result: PaginationBase<[House]> = try await APIAgentTest.shared.runRequest(endPoint: endpoint)

        self.all = result.result ?? []
        self.filtered = result.result ?? []
        self.listIsFetched = true
    } catch let error as ErrorResponse {
        
        print("Error: \(error.errorMessage)")
        self.all = []
        self.filtered = []
    } catch {
        print("Unexpected Error: \(error.localizedDescription)")
        self.all = []
        self.filtered = []
    }

    self.networking = false
}

enter image description here

Requirements:
Apple Swift version 6.0.3 Target: arm64-apple-macosx15.0

According to the information I have given above, I am trying to use this way in Task usage, but I get an error in a way I do not understand. I am providing everything requested.

What do I need to do?

I am converting the closure type network request functions to async/await structure to improve them, but I am stuck.

Upvotes: 0

Views: 107

Answers (1)

malhal
malhal

Reputation: 30746

You can use .task for async/await it is designed to replace @StateObject, just do:

.task{ // runs on appear 
   items = await fetcher.fetchItems
}

Put your fetcher struct that contains the async func in the Environment if you would like to mock it for previews.

Upvotes: 0

Related Questions