Skip to content

Commit

Permalink
demo: useReducer
Browse files Browse the repository at this point in the history
  • Loading branch information
pavi2410 committed Feb 20, 2022
1 parent 561d60b commit de7acfd
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,14 @@ sealed class ExampleScreen(
) {
object Counter : ExampleScreen("counter", "Counter", { CounterExample() })
object Context : ExampleScreen("context", "Context", { ContextExample() })
object Reducer : ExampleScreen("reducer", "Reducer", { ReducerExample() })
object Network : ExampleScreen("network", "Network", { NetworkExample() })
}

val exampleScreens
get() = listOf(
ExampleScreen.Counter,
ExampleScreen.Context,
ExampleScreen.Reducer,
ExampleScreen.Network
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package me.pavi2410.useCompose.app.screens

import androidx.compose.foundation.layout.Column
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import me.pavi2410.useCompose.react.useReducer

data class MyState(val count: Int)
data class MyAction(val type: String)

val initialState = MyState(0)

@Composable
fun ReducerExample() {
Column {
val (state, dispatch) = useReducer<MyState, MyAction>(initialState) { state, action ->
when (action.type) {
"increment" -> state.copy(count = state.count + 1)
"decrement" -> state.copy(count = state.count - 1)
else -> throw Error()
}
}

Text("Count: ${state.count}")
Button(onClick = {
dispatch(MyAction("increment"))
}) {
Text("+")
}
Button(onClick = {
dispatch(MyAction("decrement"))
}) {
Text("-")
}
}
}

0 comments on commit de7acfd

Please # to comment.