Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add state delegate for useState hook #156

Merged
merged 3 commits into from
Apr 4, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions kotlin-react/src/main/kotlin/react/hooks.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
package react

import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty

typealias RDependenciesArray = Array<dynamic>
typealias RDependenciesList = List<dynamic>

Expand All @@ -19,6 +22,25 @@ fun <T> useState(valueInitializer: () -> T): Pair<T, RSetState<T>> {
return currentValue to setState
}

private class ReactStateDelegate<T>(useState: Pair<T, RSetState<T>>) : ReadWriteProperty<Any?, T> {
private val state = useState.first

private val setState = useState.second

override operator fun getValue(thisRef: Any?, property: KProperty<*>): T =
state

override operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
setState(value)
}
}

fun <T> state(initValue: T): ReadWriteProperty<Any?, T> =
ReactStateDelegate(useState(initValue))

fun <T> state(valueInitializer: () -> T): ReadWriteProperty<Any?, T> =
ReactStateDelegate(useState(valueInitializer))

typealias RReducer<S, A> = (state: S, action: A) -> S
typealias RDispatch<A> = (action: A) -> Unit

Expand Down