How to pass a subset of state to a substore #1125
-
Lets make a quick example with "pseudo" code
When I present the UpdateUserView I do something in these lines...
I certainly get the updated user from the "appReducer" (not declared here) by simply:
But how I'm supposed to pass the user to the "UpdateUserView" for example to prefill the textField with the existing one from |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 9 replies
-
Hello @ivangodfather! extension AppState {
var updateUser: UpdateUserState {
get {
UpdateUserState(username: user.username)
}
set {
self.user.username = newValue.username
}
}
} This is more foolproof than having to account for each possible struct UpdateUserState {
var username = ""
var cursorPosition: CGPoint?
} you will lose the struct AppState {
private var _updateUser: UpdateUserState = .init()
var updateUser: UpdateUserState {
get {
var value = _updateUser
value.username = user.username
return value
}
set {
_updateUser = newValue
self.user.username = newValue.username
}
}
…
} This method is general, and can apply to almost all cases, but it could be not performant enough when your child state is a large collection. If performance is problematic, you can then either:
let appReducer = Reducer<…> {
…
}
.onChange(\user.username) { newValue, state, action, environment in
state.updateUser.username = newValue
} Each method has its pros and cons, and you may have to switch from one to another as your app evolves and you hit their own limitations. There is no silver bullet to my knowledge. |
Beta Was this translation helpful? Give feedback.
Hello @ivangodfather!
As often, there are several ways to achieve this.
The most common is to rely on a computed property that is updated on "get" and reinjected on "set". So, with your current model:
This is more foolproof than having to account for each possible
username
modification.Using this setup, a whole new
UpdateUserState
is delivered each time. It furthermore frees one stored field from yourAppState
which is always a good thing (faster automatic equatability, smaller footprint on the stack, etc.)