'How to get value (not array) from API in SwiftUI

I work with this API: https://api.spacexdata.com/v4/rockets. By some exploring I decided to use this API getter:

let rocketsData: [Rocket] = [] //<-- Spoiler: This is my problem

class Api {
    func getRockets(completion: @escaping ([Rocket]) -> ()) {
        guard let url = URL(string: "https://api.spacexdata.com/v4/rockets") else { return }
            
        URLSession.shared.dataTask(with: url) { (data, response, error) in
            do {
                let rockets = try JSONDecoder().decode([Rocket].self, from: data!)
                DispatchQueue.main.async {
                    completion(rockets)
                }
            } catch {
                print(error.localizedDescription)
            }
        }
        .resume()
    }
}

This is my Model:

struct StageInfo: Codable {
    let engines: Int
    let fuelAmountTons: Double
    let burnTimeSec: Int?
        
    enum CodingKeys: String, CodingKey {
        case engines
        case fuelAmountTons = "fuel_amount_tons"
        case burnTimeSec = "burn_time_sec"
    }
}
    
struct Rocket: Codable, Identifiable {
    let id = UUID()
    let name: String
    let firstFlight: String
    let country: String
    let costPerLaunch: Int
    let firstStage: StageInfo
    let secondStage: StageInfo
            
    enum CodingKeys: String, CodingKey {
        case id
        case name
        case firstFlight = "first_flight"
        case country
        case costPerLaunch = "cost_per_launch"
        case firstStage = "first_stage"
        case secondStage = "second_stage"
    }
}

By this model I am able to get an array of values, and I can use this array in my View with only Lists or ForEach loops. But what if I want to use not the array, but some values? In this view for example I use ForEach loop, that's why everything works perfect:

    struct ContentView: View {
        @State var rockets = [Rocket]() // <-- Here is the array I was talking about
        
        var body: some View {
            NavigationView {
                List {
                    ForEach(rockets) { item in // <-- ForEach loop to get values from the array
                        NavigationLink(destination: RocketDetailView(rocket: item)) {
                            RocketRowView(rocket: item)
                                .padding(.vertical, 4)
                        }
                    }
                } //: LIST
                .navigationTitle("Rockets")
                .toolbar {
                    ToolbarItem(placement: .navigationBarTrailing) {
                        Button(action: {
                            isShowingSettings = true
                        }) {
                            Image(systemName: "slider.horizontal.3")
                        } //: BUTTON
                        .sheet(isPresented: $isShowingSettings) {
                            SettingsView()
                        }
                    }
                } //: TOOLBAR
            } //: NAVIGATION
            .onAppear() {
                Api().getRockets { rockets in // <-- Method to get the array from the API
                    self.rockets = rockets
                }
            }
        }
    }

    //MARK: - PREVIEW
    struct ContentView_Previews: PreviewProvider {
        static var previews: some View {
            ContentView()
        }
    }

And finally here I have a View with an item that I use to create the List of this items in another View:

    struct RocketRowView: View {
        var rocket: Rocket // <-- Here I don't need to use an array as previously, so I create a usual variable with Rocket instance
        
        var body: some View {
            HStack {
                Image("Falcon-9")
                    .resizable()
                    .scaledToFill()
                    .frame(width: 80, height: 80, alignment: .center)
                    .background(Color.teal)
                    .cornerRadius(8)
                
                VStack(alignment: .leading, spacing: 5) {
                    Text(rocket.name) // <-- So this surely doesn't work
                        .font(.title2)
                        .fontWeight(.bold)
                    Text(rocket.country) // <-- And this doesn't work neither
                        .font(.caption)
                        .foregroundColor(Color.secondary)
                }
            } //: HSTACK <-- And I can't use here inside onAppear the method that I used before to get the array, because I don't need the array
        }
    }

struct RocketRowView_Previews: PreviewProvider {
    static var previews: some View {
        RocketRowView(rocket: rocketsData[0]) // <-- Because of the variable at the top of this View I have to add missing argument for parameter 'rocket' in call. Immediately after that I get an error: "App crashed due to an out of range index"
    }
}

As I wrote in the comments above I create a variable rocket of type Rocket in my RocketRowView() and because of that I have to add missing argument for parameter 'rocket' in RocketRowView_Previews. Here I get an error: "App crashed due to an out of range index". I don't understand why let rocketsData: [Rocket] = [] is empty and how I can use the rocket variable in my View without ForEach looping. Plead help me dear experts. I've already broken my brain trying to figure out for a whole week, what I should do.



Solution 1:[1]

The data in the preview area has nothing to do with the received data. If you want a preview you have to provide a custom instance.

A usual way is to add a static example property to the structs like this

struct StageInfo: Codable {
    let engines: Int
    let fuelAmountTons: Double
    let burnTimeSec: Int?
        
    enum CodingKeys: String, CodingKey {
        case engines
        case fuelAmountTons = "fuel_amount_tons"
        case burnTimeSec = "burn_time_sec"
    }

    static let firstStage = StageInfo(engines: 1, fuelAmountTons: 44.3, burnTimeSec: 169)
    static let secondStage = StageInfo(engines: 1, fuelAmountTons: 3.30, burnTimeSec: 378)

} 

struct Rocket: Codable, Identifiable {
    let id = UUID()
    let name: String
    let firstFlight: String
    let country: String
    let costPerLaunch: Int
    let firstStage: StageInfo
    let secondStage: StageInfo
            
    enum CodingKeys: String, CodingKey {
        case id
        case name
        case firstFlight = "first_flight"
        case country
        case costPerLaunch = "cost_per_launch"
        case firstStage = "first_stage"
        case secondStage = "second_stage"
    }

    static let example = Rocket(id: UUID(), name: "Falcon 1", firstFlight: "2006-03-24", country: "Republic of the Marshall Islands", costPerLaunch: 6700000, firstStage: StageInfo.firstStage, secondStage: StageInfo.secondStage)

}

Then just refer to the example

struct RocketRowView_Previews: PreviewProvider {
    static var previews: some View {
        RocketRowView(rocket: Rocket.example)
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 vadian