-1

I am using the below fuucntion to fetch Data and dispaly it. The problem is the view updates but does not sort according to id's (as I read online, @FetchRequest doesnt update view dynamically). It is only when I refresh my view, I see the sorting corrected. Is there any way out so that my view updates dynamically.

@FetchRequest (entity: ChatData.entity(), sortDescriptors: [NSSortDescriptor(key: "id",      ascending: true)])
var chatData : FetchedResults <ChatData>

ScrollView {
    VStack{
        ForEach(chatData, id: \.self) { message in
            if message.role != "system" {
                ChatCell(message: message.content ?? "", user: message.role ?? "")
            }
        }
    }//:VStack
    .padding(.horizontal)
    .listStyle(.plain)
}//:ScrollView
vadian
  • 274,689
  • 30
  • 353
  • 361
Uday Agarwal
  • 7
  • 1
  • 3

1 Answers1

0

You can't use id for an attribute name because that is used for the Identifiable protocol you'll need to rename it to something else like uid, and here is an improvement to the code using a predicate instead of an if:

@FetchRequest(sortDescriptors: [NSSortDescriptor(key: "uid", ascending: true)],
                    predicate: NSPredicate(format: "role != %@", "system"))
var chatData : FetchedResults <ChatData>

ScrollView {
    VStack{
        ForEach(chatData) { message in
            ChatCell(message: message.content ?? "", user: message.role ?? "")
        }
    }//:VStack
    .padding(.horizontal)
    .listStyle(.plain)
}//:ScrollView
malhal
  • 26,330
  • 7
  • 115
  • 133