Closed Doraemoe closed 1 year ago
@Doraemoe Your root app scene is creating a brand new store in its body, so when it detects a scene change your state is replaced with a brand new store with no path, which puts SwiftUI in a bad state. I believe you'd have the same problem in vanilla SwiftUI using an observable object.
The fix is to hold onto your store in your app so that it is never recreated:
@main
struct userdefault_tcaApp: App {
@Environment(\.scenePhase) var scenePhase
let store = Store(initialState: RootFeature.State()) {
RootFeature()
}
var body: some Scene {
WindowGroup {
ContentView(store: self.store)
}
}
}
In general you should not create new models in the body
of scenes or views as SwiftUI's observation can recreate them at any time.
Since this isn't a bug with the library, I'm going to convert it to a discussion instead.
Description
When include
@Environment(\.scenePhase) var scenePhase
in the root view and use stack based navigation, I cannot write toUserDefaults
in child view reducer.Errors:
Checklist
main
branch of this package.Expected behavior
I can write to UserDefaults in reducer
Actual behavior
Xcode throw errors
Steps to reproduce
Please see example: https://github.com/Doraemoe/tca-scenephase-userdefault
The Composable Architecture version information
1.3.0
Destination operating system
iOS 17
Xcode version information
Version 15.0.1 (15A507)
Swift Compiler version information