Roland Lariotte
Roland Lariotte

Reputation: 3498

Why is my SwiftUI List not being populating with all my data?

I have my data coming back from an api call using Combine this way:

[Animals.Dog(id: nil, name: "Bobby", age: 4), Animals.Dog(id: nil, name: "Cronos", age: 2), Animals.Dog(id: nil, name: "Willy", age: 2), Animals.Dog(id: nil, name: "Rex", age: 8)]
finished

When populating my List with the array of animals, only the first item is populated. But this same first item is displayed as much animals as they are. In this case, the first item is populated 4 times and I cannot see the three other dogs on my List.

Where are my data hidden?

import SwiftUI
import Combine

struct AnimalsView: View {

  @State private var dogs = [Dog]()

  private let networkRequest = NetworkRequest()

  //MARK: - Body
  var body: some View {
    VStack(spacing: 20) {
      TitleView()

      //MARK: Dogs list view
      List(dogs) {
        AnimalCell(name: $0.name,
                   age: $0.age)
      }
      .modifierViewList()
    }
    .onAppear {
      _ = networkRequest.downloadAnimals()
        .sink(receiveCompletion: {
          print($0)
        },receiveValue: { (animal) in
          self.dogs = animal.dogs
          print(animal.dogs)
        })
    }
  }
}

//MARK: Network request
extension NetworkRequest {
  func downloadAnimals() -> AnyPublisher<Animal, Error> {
    URLSession.shared
      .dataTaskPublisher(for: EndPoint.rates.url)
      .receive(on: networkQueue)
      .map(\.data)
      .decode(type: Animal.self, decoder: JSONDecoder())
      .mapError { (error) -> NetworkRequest.Error in
        switch error {
        case is URLError:
          return Error.addressUnreachable(EndPoint.rates.url)
        default:
          return Error.invalidResponse
        }
    }
    .eraseToAnyPublisher()
  }
}

Upvotes: 1

Views: 148

Answers (2)

Hardik Bar
Hardik Bar

Reputation: 1760

[Animals.Dog(id: 1, name: "Bobby", age: 4), Animals.Dog(id: 2, name: "Cronos", age: 2), Animals.Dog(id: 3, name: "Willy", age: 2), Animals.Dog(id: 4, name: "Rex", age: 8)]

Upvotes: 0

Procrastin8
Procrastin8

Reputation: 4503

If Animal.Dog conforms to Identifiable, all your data has the same id, namely nil. Therefore, List thinks you only have one distinct Animal.Dog, the first with id of nil. Try giving them actual ids.

Upvotes: 3

Related Questions