Home > Net >  How to show/Hide view on API response in swiftui?
How to show/Hide view on API response in swiftui?

Time:11-21

I am trying to show the view on a condition but the data is coming from the API so the code executed before the API response but I want to run the code after API response, how can I do that in swiftUI app?

class DashboardViewModel: ObservableObject {
    
    var poCount:[TaskCount]?
    
    @State var totalApprovalCount = 0



func getData() {

    APIService.shared.makeApiTypeRequest(url: APIURLConstant.poTaskCountUrl, param: nil, methodType: .get, expecting: [TaskCount].self, passToken: true) { result in
                switch result {
                case .success(let respData):
                    DispatchQueue.main.async {
                        self.rcCount = respData
                        print("fetchRCCount called \(respData.count)")
                        if respData.count > 0 {
                            self.totalApprovalCount  = respData[0].count ?? 0
                        }
                        
                        if respData.count > 1 {
                            self.totalApprovalCount  = respData[1].count ?? 0
                        }
                    }
                case .failure(let error):
                    if error as! CustomError == CustomError.tokenExpired {
                        DispatchQueue.main.async {
                            
                        }
                    }
                }
            }

}

view:

struct DashboardCombinedView: View {
    @ObservedObject var dashboardModel = DashboardViewModel()
    var body: some View {
        VStack {
            
            if dashboardModel.totalApprovalCount > 0 {
                Text("My custom view")
            }
      }.onAppear(){
        dashboardModel.getData()
      }
}

the condition if dashboardModel.totalApprovalCount > 0 { is always gets false as it depends on the API response, how can I check this condition after API call?

CodePudding user response:

To observe objects you should use @StateObject in your view and publish any change by @Published identifier:

class DashboardViewModel: ObservableObject {
    @Published var totalApprovalCount = 0

    var poCount: [TaskCount]?

    func getData() {
        // calling api
    }
}

and view:

struct DashboardCombinedView: View {
    @StateObject private var dashboardModel = DashboardViewModel()

    var body: some View {
        VStack {
            if dashboardModel.totalApprovalCount > 0 {
                Text("My custom view")
            }
        }
        .onAppear {
            dashboardModel.getData()
        }
    }
}
  • Related