Using @Dependency inside State #2326
-
I've run into issues where I want a variable on state to be different based on a Dependency passed in. The problem as I see it though is that @dependency is only guaranteed to be accurate if used inside the Reducer body/reduce variable/func and putting an @dependency in State will not work properly if called from a View (because usually you override the Dependency inside the Reducer body var). Example code of what I want to do:
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
If the computed property is only on your state so it can be read by the view, perhaps to display something conditionally, maybe it's more appropriate to be put in the Either way, as you acknowledge, accessing the dependency in a computed property on state doesn't feel quite right to me, because it makes your state not-inert. |
Beta Was this translation helpful? Give feedback.
-
There's another option. You can use struct State {
var showNewNav: Bool
init() {
@Dependency(\.flags) var featureFlags
self.showNewNav = featureFlags.enabled && featureFlags.showNewNav
}
} |
Beta Was this translation helpful? Give feedback.
There's another option. You can use
@Dependency
in the initializer of your state rather than accessing it in the computed property. State is always created inside a reducer, and therefore it is covered by the cascading rules ofwithDependencies
: