SwiftData updates delay in widget

My SwiftData model doesn't have time to update, and the widget gets old data on the timeline

I create simple SwiftData app with widget extension. To share swiftdata between widget and app I use the same approach as in sample code "Adopting SwiftData for a Core Data app":

let modelContext = ModelContext(DataModel.shared.modelContainer)

if let models = try? modelContext.fetch(fetchDescriptor) {
   // use 
}

After I create/delete/updated model I call:

WidgetCenter.shared.reloadAllTimelines()

The problem is that the widget receives outdated data as a result of modelContext.fetch. To get the new data I need to call WidgetCenter.shared.reloadAllTimelines() twice or with some delay:

// MyModelEditorView
private func save() {
    if let myModel {
      myModel.title = title
    } else {
      let myModel = MyModel(
        title: title
      )
      
      modelContext.insert(word)
    }

    WidgetCenter.shared.reloadAllTimelines()
    // i have to call it twice
    WidgetCenter.shared.reloadAllTimelines()
  }

I couldn't test SampleCode for similar update behavior, because somehow I couldn't get the models into the widget and I only have "No Trip" displayed there.

If I remove the second call, the UI is updated immediately and the new title is displayed, but the widget in the timeline receive the old title.

I don't understand whether this is the case and I need to update the widget with a delay or am I doing something wrong?

BTW: Why is sample code in init we don't use shared container?

    private let modelContainer: ModelContainer
    
    init() {
        do {
           // why we don't use DataModel.shared.modelContainer
            modelContainer = try ModelContainer(for: Trip.self)
        } catch {
            fatalError("Failed to create the model container: \(error)")
        }
    }

The issue might be with the timeline provider. But basing solely on your code, try reloading the widget right after you insert it.

Like this:

modelContext.insert(word)
WidgetCenter.shared.reloadAllTimelines()
SwiftData updates delay in widget
 
 
Q