Should I use environment directly in actions? #1367
-
I wonder if it is wrong to use the environment directly in actions. I know that the recommendation is to use it in effects only. However, in my case, I would like to read some settings from user defaults synchronously in my So I'm struggling a little if I should limit environment usage only to effects or not. I guess this breaks a little the principle of pure function. Now transformation depends on the external world. Or maybe in this case I should pass my user defaults setting through onAppear action in an associated value? But then my view would have to know how to access settings from the environment. My case: switch action {
case .onAppear:
state.data = env.settings.someData
return .none
} Another example: switch action {
case .someAction:
return .task { .permissionChecked(env.hasLocationPermission) }
case .permissionChecked(let hasPermission):
if hasPermission {
return .task { ... }
} else {
return .task { ... }
}
Which seems to be a boilerplate, a little. And each place like that triggers some reloads on UI layer. Or I could do: switch action {
case .someAction:
if env.hasLocationPermission {
return .task { ... }
} else {
return .task { ... }
}
What would be the correct approach in those scenarios? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hi @wojciech-kulik, we should really write up some documentation about this, but we feel that the kinds of synchronous effects you are describing are totally fine. In particular, effects that just need to access some value from the "outside world", and such that that access is fast. So, things like reading from user defaults directly is totally fine to do synchronously directly in the reducer. On the other hand, a database query might still be best to handle in an async fashion since it may time some time to execute and that could hold up the main thread. |
Beta Was this translation helpful? Give feedback.
Hi @wojciech-kulik, we should really write up some documentation about this, but we feel that the kinds of synchronous effects you are describing are totally fine. In particular, effects that just need to access some value from the "outside world", and such that that access is fast.
So, things like reading from user defaults directly is totally fine to do synchronously directly in the reducer. On the other hand, a database query might still be best to handle in an async fashion since it may time some time to execute and that could hold up the main thread.