How do I access a variable that's using the @Query wrapper in other views?

35 views Asked by At

I'm brand new to swift, and I've been learning how to use SwiftData at a basic level. I have an array of Item objects called "items" that is using the @Query wrapper so that it updates whenever its data is changed. I'd like to access the contents of the array in another view, so that I can sort the Items into folders.

Here is the view the array is initialized in:

struct ItemsListView: View {
    @Environment(\.modelContext) var modelContext
    @Query var items: [Item]

var body: some View {
    if !items.isEmpty {
        Text("Swipe left to delete items.")
            .foregroundColor(Color.gray)
            .multilineTextAlignment(.leading)
    }
        List {
            ForEach(items) { item in
                NavigationLink(value: item) {
                    Text(item.itemName)
                }
            }
                .onDelete(perform: deletePeople)
        }
        .overlay{
            if items.isEmpty {
                ContentUnavailableView(label: {
                    Label("No Items", systemImage: "circle.grid.3x3.fill")
                }, description: {
                    Text("Click the plus to add items.")
                })
            }
        }

}

And the view I'd like to use the array in:

    struct addFolderSheet: View {
    @Environment(\.dismiss) private var dismiss
    @Environment(\.modelContext) var modelContext
    @State private var name: String = ""
    
    
    var body: some View {
        NavigationStack{
            Form {
                Section{
                    TextField("Folder Name", text: $name)
                }
                Section("Select Items to Sort"){
                    //doesn't work since I can't access the items array
                    ForEach(items) { item in
                    Text(item.itemName)

                    }
                }
            }
            .navigationTitle("New Folder")
            .toolbar {
                ToolbarItemGroup(placement: .topBarLeading) {
                    Button("Cancel") {dismiss()}
                }
                ToolbarItemGroup(placement: .topBarTrailing) {
                    Button("Save") {
                        let folder = Folder(folderName: name, items: [])
                        dismiss()
                    }
                }
            }
        }
    }
}

I can't add a second wrapper to the same variable, so I'm not sure how I would go about allowing the variable to perform the same way while also allowing it to be accessed by other views.

0

There are 0 answers