What is the recommended approach to maintain state...
# compose
a
What is the recommended approach to maintain states, validate and show errors for a form having around 10 textfields? I am using Material’s
OutlineTextField
. To maintain each textfield’s own state, I am using custom TextFieldState as in JetSurvey. As a result, I had to declare 10 states to remember in composable which I tried to solve by moving them into UILogic entity [ Code in thread ], because I think it is related to UI, rather than business. Apart from these textfields, there are also states maintained for bottom sheet and selections. What is the rule of thumb to keep state in composable vs view model? How can I avoid clutter composable with so many states? I found articles by Google guys suggesting to put textfield states in view model. Need suggestions.. Thank you.
Inside composable:
Copy code
@Composable
fun SignupScreenContent(state: SignupState) {

    val uiState = rememberSignupUIState(
        firstNameState = getState(field = FirstName),
        lastNameState = getState(field = LastName),
        phoneState = getState(field = Phone),
        emailState = getState(field = Email) as EmailState,
        passwordState = passwordState,
        confirmPasswordState = getConfirmPasswordState(passwordState = passwordState),
        streetState = getState(field = Street),
.....)

var loginBottomSheetState by remember { mutableStateOf(LoginBottomSheetState()) }

}
Copy code
@Composable
private fun getState(field: SignupField): TextFieldState {
    val errorName = stringResource(id = R.string.error_name)
    val errorPhone = stringResource(id = R.string.error_phone)
....

    return when (field) {
        FirstName, LastName -> TextFieldState(
            validator = { it.length >= 3 },
            errorMessage = { errorName })
        Phone -> TextFieldState(validator = { it.length == 10 }, errorMessage = { errorPhone })
.......
}
u
rule of the thumb is lifecycle. if you push a new screen and then back, do you want you'r form state to die?
a
Thanks for reply. I want to maintain the state. Doesn't it depend upon business vs UI logic?
u
not sure what you mean by that if you want to scope the state to view then keep it there jf you want to scope it to screen keep it in viewmodel
👍 1