Mdoyle1
Mdoyle1

Reputation: 121

Display a list from Observable Object SwiftUI

I'm trying to decode some JSON and print it to a list, currently getting this error message,

ForEach, Int, Text> count (626) != its initial count (0). ForEach(_:content:) should only be used for constant data. Instead conform data to Identifiable or use ForEach(_:id:content:) and provide an explicit id!

I can print a specific ticket by accessing result[0] but I'm not able to return all results to the view.

Here is my ListView

struct WOListView: View {
    @EnvironmentObject var ticketData:ControlCenter


    var body: some View {

        VStack {
            Text(String(self.ticketData.jsonData?.result[0].ticketID?.ticketID ?? 0))

            List{
                ForEach(0 ..< (self.ticketData.jsonData?.result.count ?? 0)) {
                    Text(String(self.ticketData.jsonData?.result[$0].ticketID?.ticketID ?? 0))
                }

                }
            }
        }

    }


struct WOListView_Previews: PreviewProvider {
    static var previews: some View {
        WOListView().environmentObject(ControlCenter())
    }
}

WorkOrderResults.swift

struct WorkOrderResults: Codable{

    var result:[Result]
    enum CodingKeys:String, CodingKey{
         case result = "Result"
     }

    struct Result:Codable{

        var ticketID:TicketID?
        var summary:Summary?
        var status:Status?
        var catagory:Catagory?

        enum CodingKeys:String, CodingKey{
            case ticketID = "1"
            case summary = "22"
            case status = "96"
            case catagory = "164"
        }

        struct TicketID:Codable {
            var ticketID:Int?
            enum CodingKeys: String, CodingKey{
                case ticketID = "Value"
            }
        }

Upvotes: 0

Views: 579

Answers (1)

Mdoyle1
Mdoyle1

Reputation: 121

Found the answer to my question here! view-is-not-rerendered-in-nested-foreach-loop!

Change WOListView to look like this...

 var body: some View {

        VStack {
            Text(String(self.ticketData.jsonData?.result[0].ticketID?.ticketID ?? 0))


               ForEach(0 ..< (self.ticketData.jsonData?.result.count ?? 0), id: \.self) {
                    Text(String(self.ticketData.jsonData?.result[$0].ticketID?.ticketID ?? 0))


                }
            }
        }

Upvotes: 1

Related Questions