Hello everyone!
I have a simple edit page to update a user profile. My UserProfile is something like that:
data class UserProfile(var name: String, var email: String, var password: String)
Inside my view model, I have something like that:
class ViewModel {
var userProfile by mutableStateOf(UserProfile())
}
And now I use it like that:
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:
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:
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:
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! 🙂