@State variable returns empty despite being set in .onAppear function

With the code below, JSON data is parsed and is stored in the variable data in the .onAppear function, however an empty set of data is passed to the Content view. How can that be fixed so that the JSON data passes to the DataView?

struct ContentView: View {
    @State var data: [Data]
    @State var index: Int = 0
    
    var body: some View {
        VStack {
            DataView(data: data[index])
        }
        .onAppear {
            let filePath = Bundle.main.path(forResource: "data", ofType: "json")
            let url = URL(fileURLWithPath: filePath!)
                
            data = getData(url: url)
        }
    }
    
    func getData(url: URL) -> [Data] {
        do {
            let data = try Data(contentsOf: url)
            let jsonDecoded = try JSONDecoder().decode([Data].self, from: data)
            
            return jsonDecoded
        } catch let error as NSError {
            print("Fail: \(error.localizedDescription)")
        } catch {
            print("Fail: \(error)")
        }
        
        return []
    }
}
Answered by Claude31 in 853587022

That's the error I told you in a previous post.

    @State var datum: Data

Replace with

    var datum: Data

If tha works, don't forget to close the thread by marking this answer as correct. Otherwise, explain.

Finally, to give you in depth explanation about the use of @State in DataView: https://forums.swift.org/t/im-so-confused-why-state-var-inside-a-view-do-not-change-when-you-call-a-method-on-this-view-from-some-outer-view/31944/7

And you can test with a Binding:

struct DataView2: View {
    
    @Binding var datum: Data2
    var body: some View {
        Text("DataView \(datum.str)")
    }
}

calling it with

DataView2(datum: $data[index])

Good continuation.

Finally, to give you in depth explanation about the use of @State in DataView: https://forums.swift.org/t/im-so-confused-why-state-var-inside-a-view-do-not-change-when-you-call-a-method-on-this-view-from-some-outer-view/31944/7

And you can test with a Binding:

struct DataView2: View {
    
    @Binding var datum: Data2
    var body: some View {
        Text("DataView \(datum.str)")
    }
}

calling it with

DataView2(datum: $data[index])

Good continuation.

@State variable returns empty despite being set in .onAppear function
 
 
Q