0

I have created a very simple test in SwiftUI:

Pokemon

struct Pokemon: Identifiable {
    let id: Int
    let name: String
}

PokemonList

struct PokemonList: View {
    @State private var pokemonList: [Pokemon] = []
    
    var body: some View {
        List(pokemonList) {
            PokemonRow(pokemon: $0)
        }
        .listStyle(PlainListStyle())
        .onAppear {
            DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                // Here I fill Pokemon list from API
            }
        }
    }
    
    init(_ pokemonList: [Pokemon] = []) {
        self.pokemonList = pokemonList
    }
}

#if DEBUG
struct PokemonList_Previews: PreviewProvider {
    static var previews: some View {
        PokemonList([
            Pokemon(id: 1, name: "Bulbasaur"),
            Pokemon(id: 25, name: "Pikachu"),
            Pokemon(id: 150, name: "Mewtwo")
        ])
    }
}
#endif

PokemonRow

struct PokemonRow: View {
    var pokemon: Pokemon
    
    var body: some View {
        HStack(alignment: .center) {
            Text("#\(pokemon.id)")    
            Text(pokemon.name)
        }
        .padding()
        .frame(height: 50)
    }
}

#if DEBUG
struct PokemonRow_Previews: PreviewProvider {
    static var previews: some View {
        PokemonRow(pokemon: Pokemon(id: 25, name: "Pikachu"))
    }
}
#endif

The PokemonRow preview works fine, and the API call too (the list is correctly filled after the view appears), but for some reason the PokemonList preview always displays empty content. Why is that?

Thank you for your help

Another Dude
  • 1,204
  • 4
  • 15
  • 33
  • Try using `.task {...}` instead of `.onAppear {...}`, and call an `async` function to download the Pokemon objects. Update the `@State var` inside that closure; there's no need to use a delay like `asyncAfter`. – HunterLion May 13 '22 at 21:52

1 Answers1

0
init(_ pokemonList: [Pokemon] = []) {
    self._pokemonList = State(initialValue: pokemonList) // << @State init
}
ChrisR
  • 9,523
  • 1
  • 8
  • 26
  • 1
    It would be helpful to explain more about how this solves the problem, something like [this post](https://stackoverflow.com/questions/56691630/swiftui-state-var-initialization-issue) – Mark Brownsword May 14 '22 at 05:48