Stack based navigation throw error when write to userdefault in reducer and use scenePhase environment key #2535
-
DescriptionWhen include Errors:
Checklist
Expected behaviorI can write to UserDefaults in reducer Actual behaviorXcode throw errors Steps to reproducePlease see example: https://github.com/Doraemoe/tca-scenephase-userdefault The Composable Architecture version information1.3.0 Destination operating systemiOS 17 Xcode version informationVersion 15.0.1 (15A507) Swift Compiler version informationswift-driver version: 1.87.1 Apple Swift version 5.9 (swiftlang-5.9.0.128.108 clang-1500.0.40.1)
Target: x86_64-apple-macosx14.0 |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
@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 Since this isn't a bug with the library, I'm going to convert it to a discussion instead. |
Beta Was this translation helpful? Give feedback.
@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:
In general you should not create new models in the
body
of scenes or views as…