How can you make a TextField update text with SwiftData / CloudKit?

Hi all,

I have a SwiftUI-SwiftData-CloudKit app that has a TextField. I would like to make it so that after a user types in text, it will update the TextField on another device via CloudKit. I have the following code:

{
    private let comment:Comment
    
    @Query private var comments: [Comment]
    
    @State private var text: String = ""
    @State private var userInput = ""
    
    private var filteredComment: Comment?
    {
        if let comment = self.comments.first(where: { $0 == self.comment })
        {
            return comment
        }
        else
        {
            return nil
        }
    }
    
    init(comment: Comment)
    {
        self.comment = comment
    }
    
    var body: some View
    {
        VStack
        {
            if let filteredComment = self.filteredComment
            {
                TextField("", text: self.$text)
                .onAppear()
                {
                    self.text = filteredComment.text
                }
                .onChange(of: self.text)
                {
                    filteredComment.text = text
                }
            }
        }
    }
}

This code actually works fine and will update to another device via CloudKit when a user exits out of the view and then reloads it. But I would like for it to update to the TextField after the user finishes typing or while they're typing. Weirdly, it will update on the fly in another screen I have in the app that displays the same text in a list. I've tried saving the modelContext after loading self.filteredComment and it makes no difference. Anyone know what's going on here? Thanks.

Just I idea, I did not test.

Try with onReceive modifier instead of onChange.

@Claude31 Thanks I will try that out and report back.

How can you make a TextField update text with SwiftData / CloudKit?
 
 
Q