InsideLoop
InsideLoop

Reputation: 6255

Update view with SwiftData without a direct query

I have a one-to-many relationship in between my models Class ans Student. As I would like to display all the students that belong to a class, I cannot easily do that with a @Query. Therefore, my code looks like

struct ClassView: View {
    @Environment(\.modelContext) private var modelContext
    var class: Class

    var body: some View {
        List {
            ForEach(class.students!.sorted { $0.lastName < $1.lastName })
            { student in
                ...
            }
        }
    }

    func addStudent() {
        let newStudent = Student()
        modelContext.insert(newStudent)
        newStudent.class = self.class
    }
}

This view also has some code that calls addStudent when a button is pressed. Unfortunately, unlike an array of students given back with @Query, the view does not get any update when we add a student to the Class.

Is it the right way to get the students that belong to the class? (I'm a bit skeptical as I cannot find a solution with a @Query)

What can I do to trigger an update of the View when I add a new student? If there any method I can call just after adding the new student to the class?

Upvotes: 0

Views: 668

Answers (1)

Joakim Danielson
Joakim Danielson

Reputation: 51973

Since it's the Class property you are showing in the view you need to update it with the new student rather than the other way around.

So replace newStudent.class = self.class with

class.students.append(newStudent)

and the view will update with the new Student

Hopefully this is some kind of bug so that when it's fixed it won't matter which end of the relationship we update

Upvotes: 2

Related Questions