SwiftUI State not reliable updating

Hello,

I have a SwiftUI view with the following state variable:

    @State private var startDate: Date = Date()
    @State private var endDate: Date = Date()
    
    @State private var client: Client? = nil
    @State private var project: Project? = nil
    @State private var service: Service? = nil
    
    @State private var billable: Bool = false

Client, Project, and Service are all SwiftData models. I have some view content that binds to these values, including Pickers for the client/project/service and a DatePicker for the Dates.

I have an onAppear listener:

.onAppear {
            switch state.mode {
            case .editing(let tt):
                Task {
                    await MainActor.run {
                        startDate = tt.startDate
                        endDate = tt.endDate
                        client = tt.client
                        project = tt.project
                        service = tt.service
                        billable = tt.billable
                    }
                }
            default:
                return
            }
        }

This works as expected. However, if I remove the Task & MainActor.run, the values do not fully update. The DatePickers show the current date, the Pickers show a new value but tapping on them shows a nil default value.

What is also extremely strange is that if tt.billable is true, then the view does update as expected.

I am using Xcode 15.4 on iOS simulator 17.5. Any help would be appreciated.

onAppear is too late to set state. You should have the state configured first, then body is designed to create all the Views depending on the state. This is a crucial part of SwiftUI's design where "views are a function of state".

onAppear is designed for external actions unrelated to state.

Since you are using SwiftData it's not @State it is @Query to fetch the models and then bind the Views directly to them. If the types are different you can use computed bindings to convert.

SwiftUI State not reliable updating
 
 
Q