I am new to Jetpack Compose and am having a problem with the hoisting topic. I have created a very basic app with a button, the app displays the amount of times you have clicked the button. I have tried to hoist the state from one composable to another. The second composable allows you to choose by how much should the increase be by each button click. I know it is possible to achieve everything in one composable but i have decided to hoist the state to the 2nd composable so could practice hoisting. Thanks
//Composable that the state has been hoisted to
@Composable
fun chooseYourIncrease(){
var count by remember { mutableStateOf(0) }
simpleCounter(countHold = {count + 2})
}
@Composable
fun simpleCounter (countHold:(Int)->Unit,
modifier: Modifier = Modifier
){
Column(horizontalAlignment = Alignment.CenterHorizontally){
Text("Please press button to increase value", fontSize = 20.sp)
Spacer(modifier = Modifier.height(20.dp))
Button(onClick = { countHold}) {
Text(text = "Press to increase")
}
Spacer(modifier.height(20.dp))
Text ("The new value is $countHold", fontSize = 20.sp)
}
}
I get the following output on my screen
Your code has several issues:
countHold
lambda does nothing, it needs to actually change thecount
statecount
state and button logic separatelyonClick
handler doesn't need anInt
,count
state will be changed where it is hoisted