Skip to content

Commit

Permalink
Add REffectBuilder (#470)
Browse files Browse the repository at this point in the history
  • Loading branch information
turansky authored Jun 5, 2021
1 parent b968d40 commit cd62bc2
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions kotlin-react/src/main/kotlin/react/REffectBuilder.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
@file:Suppress("NOTHING_TO_INLINE")

package react

// TODO: make external in IR
class REffectBuilder
private constructor() {
inline fun cleanup(
noinline block: RCleanup,
) {
asDynamic().push(block)
}
}

internal fun useEffectCallback(
effect: REffectBuilder.() -> Unit,
): () -> RCleanup? =
useCallback(effect) {
val cleanups = arrayOf<RCleanup>()
effect(cleanups.unsafeCast<REffectBuilder>())
buildCleanup(cleanups)
}

private fun buildCleanup(
cleanups: Array<out RCleanup>,
): RCleanup? {
if (cleanups.isEmpty())
return undefined

return {
for (cleanup in cleanups)
cleanup()
}
}

0 comments on commit cd62bc2

Please sign in to comment.