Hello everyone! I have a simple edit page to updat...
# compose-web
s
Hello everyone! I have a simple edit page to update a user profile. My UserProfile is something like that:
Copy code
data class UserProfile(var name: String, var email: String, var password: String)
Inside my view model, I have something like that:
Copy code
class ViewModel {
  var userProfile by mutableStateOf(UserProfile())
}
And now I use it like that:
Copy code
fun EditProfileScreen(viewModel: ViewModel) {
  TextInput(value = viewModel.userProfile.email, attrs = {
    onInput { viewModel.userProfile.email = it.value }
  }
}
Now, from what I experienced / understand, if I modify a field from my user profile, I can’t modify it directly like I did. I would have to do something like that:
Copy code
viewModel.userProfile = viewModel.userProfile.copy(email = newEmail)
I need to copy the whole object because Compose won’t be able to detect a change and won’t trigger a recompose. And when copying, it’s a new object and this will recompose. Now is the copy way of doing thing would be the best way? Or should I do expand my UserProfile with multiple state like:
Copy code
class ViewModel {
  private var userProfile = UserProfile()
  var email by mutableStateOf(userProfile.email)
  var name by mutableStateOf(userProfile.name)
}
And edit them directly and when I click save, I would get the current value from all states. Or have states as read only and then have setter function to update the main class:
Copy code
val email by mutableStateOf(userProfile.email)
  private set

fun setEmail(newEmail) {
  userProfile.email = newEmail
  email = newEmail
}
Or is there any other way of doing this that I don’t think of? Thanks! 🙂
Modifiying a “complex” object doesn’t seems like a common practice from what I saw in all examples. It’s always a primitive type: String, Int or Boolean 😒
r
As you noted, mutable data classes as state are a no-go, but immutable data classes on the other hand are fine to use as state -- replace
var
with
val
in
UserProfile
. Its perfectly fine to use the
copy
method to update the view model.
Most of the information at https://developer.android.com/jetpack/compose/state is valid for compose-web.
If warranted, consider MVI frameworks such as Ballast or MVIKotlin to put some structure around your use of state and view models.
s
Thanks for the comments! I’ll take a look at those libraries. So changing all properties of
UserProfile
from
var
to
val
should not change anything mutable state wise but it will force me to use the
copy
function on my mutable state
r
Right
s
Thanks!