arraysswiftswiftuiasync-awaitviewmodel

Swift UI view only displaying one record instead of the List of record


I'm using Swift UI . I'm using async and await to handle the concurrency. I am trying to display list of product record .I have 30 record into json here is the json link https://dummyjson.com/products. and I got the 30 record when I debug it but when I run the app , It only displaying one record only . I am wondering where is mistake or changes , I need to make .

Here is my model ..

import Foundation

// MARK: - Welcome
struct ProductData: Codable, Hashable {
    let products: [Product]
}

// MARK: - Product
struct Product: Codable, Hashable {
    let id: Int
    let title, description: String
    let price: Int
    let discountPercentage, rating: Double
    let stock: Int
    let brand, category: String
    let thumbnail: String
    let images: [String]
}

Here is my view model code ..

@MainActor
final class ProductListViewModel {

    @Published private(set) var productLists: [ProductData] = []
    @Published private(set) var customError: NetworkError?
    @Published private(set) var refreshing = true
    @Published var isErrorOccured = false

    private let repository: ProductRepository
    init(repository: ProductRepository) {
        self.repository = repository
    }
}
extension ProductListViewModel: ProductListViewModelAction {
    func getProductList(urlStr: String) async {
            refreshing = true
            guard let url = URL(string: urlStr) else {
            self.customError = NetworkError.invalidURL
            refreshing = false
            isErrorOccured = false
            return
        }
        do {
            let lists = try await repository.getList(for: url)
            refreshing = false
            isErrorOccured = false
            productLists = [lists]

        } catch {
            refreshing = false
            isErrorOccured = true
            customError = error as? NetworkError
        }
    }
}

Here is my view ..

import SwiftUI

struct ProductListView: View {
    
    @StateObject var viewModel = ProductListViewModel(repository: ProductRepositoryImplementation(networkManager: NetworkManager()))

    var body: some View {
        NavigationStack {
            VStack {
                if viewModel.customError != nil && !viewModel.refreshing {
                    alertView()
                } else {
                    if viewModel.refreshing {
                        progressView()
                    }
                    if viewModel.productLists.count > 0 && !viewModel.refreshing {

                        List(viewModel.productLists, id: \.self) { product in
                            ProductListViewCell(productData: product)

                        } .listStyle(.grouped)
                    }
                }
            }
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    getToolBarView()
                }
            }
            .navigationTitle(Text("Product List"))
        }.task{
            await getDataFromAPI()
        }
        .refreshable {
            await getDataFromAPI()
        }
    }

    func getDataFromAPI() async {
        await viewModel.getProductList(urlStr: NetworkURL.productUrl)
    }

    @ViewBuilder
    func getToolBarView() -> some View {
        Button {
            Task{
                await getDataFromAPI()
            }
        } label: {
            HStack {
                Image(systemName: "arrow.clockwise")
                    .padding(.all, 10.0)
            }.fixedSize()
        }
        .cornerRadius(5.0)
    }

    @ViewBuilder
    func progressView() -> some View {
        VStack{
            RoundedRectangle(cornerRadius: 15)
                .fill(.white)
                .frame(height: 180)
                .overlay {
                    VStack {
                        ProgressView().padding(50)
                        Text("Please Wait Message").font(.headline)
                    }
                }
        }
    }

    @ViewBuilder
    func alertView() -> some View {
        Text("").alert(isPresented: $viewModel.isErrorOccured) {
            Alert(title: Text("General_Error"), message: Text(viewModel.customError?.localizedDescription ?? ""),dismissButton: .default(Text("Okay")))
        }
    }
}

Here is my cell view ..

import SwiftUI

struct ProductListViewCell: View {
    let productData: ProductData
    var body: some View {
        HStack {
            if let url = URL(string: productData.products.first?.thumbnail ?? ""){
                ProductAsyncImageView(url: url)
                    .frame(width: 150, height: 150)
                    .mask(RoundedRectangle(cornerRadius: 16))
            }
            VStack(alignment: .leading,spacing: 5){
                Text("Product Name: " +  (productData.products.first?.title ?? ""))
                    .frame(maxWidth: .infinity, alignment: .leading)
                    .font(.headline)

                Text("Product Description: " + (productData.products.first?.description ?? ""))
                    .frame(maxWidth: .infinity, alignment: .leading)


                Text("Product Price: " + String(productData.products.first?.price ?? 0))
                    .frame(maxWidth: .infinity, alignment: .leading)
                    .font(.subheadline)
            }
        }
    }
}

Here is the result in the debug ..

Debug result

Here is the screenshot..Only one record is displayed.

enter image description here


Solution

  • The productLists = [lists] creates an array with one item in it. Now, that ProductData might have thirty products in it, but ProductListViewCell then creates a cell for only the first product in that ProductData. Thus, only one item will be shown.

    I would suggest product list view model should probably just take an array of products:

    final class ProductListViewModel: ObservableObject {
        @Published private(set) var products: [Product] = []    // an array of products
    
        …
    }
    
    extension ProductListViewModel {
        func getProductList(urlStr: String) async {
            refreshing = true
            guard let url = URL(string: urlStr) else { … }
    
            do {
                let productList = try await repository.getList(for: url)
                refreshing = false
                isErrorOccured = false
                products = productList.products                 // get the list of products
            } catch {
                …
            }
        }
    }
    

    The then the ProductListView would show this array of Product:

    struct ProductListView: View {
        @StateObject var viewModel = …
        
        var body: some View {
            NavigationStack {
                VStack {
                    …
                    if viewModel.products.count > 0 && !viewModel.refreshing {
                        List(viewModel.products, id: \.self) { product in
                            ProductListViewCell(product: product)
                        } .listStyle(.grouped)
                    }
                }
    } 
    

    The cell then just takes a Product:

    struct ProductListViewCell: View {
        let product: Product
        
        var body: some View {
            HStack {
                if let url = URL(string: product.thumbnail) { … }
    
                VStack(alignment: .leading, spacing: 5) {
                    Text("Product Name: \(product.title)")
                        .frame(maxWidth: .infinity, alignment: .leading)
                        .font(.headline)
                    
                    Text("Product Description: \(product.description)")
                        .frame(maxWidth: .infinity, alignment: .leading)
                    
                    Text("Product Price: \(product.price)")
                        .frame(maxWidth: .infinity, alignment: .leading)
                        .font(.subheadline)
                }
            }
        }
    }
    

    Yielding:

    enter image description here


    Now, there are lots of ways of skinning the cat: You can use your ProductData if you want. But the key take-home message is that ProductListViewCell is for showing a single Product so it does not make sense to give it a whole ProductData and only access the first product in that array of 30 products contained within the ProductData.