0

I am a beginner at Swift and SwiftUI and I have a problem showing the completion data inside of ForEach in SwiftUI.

I know I am getting the data, because I can print it on the console, but I can't show it in view.

Here is my view model:

func getCurrentPrice(selectedCoin: String, completionBlock: @escaping (Double) -> Void) {
    specificCoinRepository.getSpecificCoin(selectedCoin: selectedCoin) { result in
        switch result {
            
        case .success(let specificCoinModel):
            if let selectedCoinCurrentPrice = specificCoinModel.marketData?.currentPrice["usd"] {
                completionBlock(selectedCoinCurrentPrice)
            }

        case .failure(let error):
            print(error)
        }
    }
}

And here is the View:

VStack {
    LazyVGrid(columns: gridForm) {
        ForEach(favouriteAssetViewModel.favouriteCoins, id: \.self) { asset in
            UserAssetCardView(name: asset.name ?? "", symbol: asset.symbol ?? "", priceChangePercentage: 2, currentPrice: self.currentPrice, imgURL: asset.imgURL ?? "", purchaseQuantity: asset.purchaseQuantity ?? 0, animation: animation, addButtonAnimate: addButtonAnimate, isAddedToPorfolio: isAddedToPorfolio, isTouched: $isTouched)
            .task {
                specificCoinVM.getCurrentPrice(selectedCoin: asset.id ?? "") { price in
                    self.currentPrice = price //I want to show this data in each UserAssetCardView
                    print(price)
                }
            }
        }
    }
}
j-kobu
  • 3
  • 2
  • Instead of a completion block, store the result on a `@Published` property on your `ObservableObject` – jnpdx Apr 22 '22 at 18:29
  • @jnpdx I have tried this before, but the problem with this is just showing the same data for all cards. And when the view appears for the first time, it doesn't show any data. – j-kobu Apr 22 '22 at 18:37
  • Well, you could refactor so that you do the `task` on `UserAssetCardView` and store the result in a `@State` variable, or you could store the results (plural) in `specificCoinVM` in a `@Published` dictionary keyed by asset id. – jnpdx Apr 22 '22 at 18:38
  • @jnpdx I have refactored the function and deleted the completion block part. I have created a "@Published" var currentPrice: [String : Double] = [ : ], and inside the function I have assigned key : value like this self.currentPrice[selectedCoin] = selectedCoinCurrentPrice. It didn't work either. It is like the same I have commented on before with the "@Published" property. I don't know why the console shows the data instead of the view and just when the view is showing for the second time. – j-kobu Apr 22 '22 at 19:14
  • You'd have to edit your question with the relevant code -- too hard to read in the comments and it seems like there's context missing. – jnpdx Apr 22 '22 at 19:16

0 Answers0