Skip to content

Commit

Permalink
Fix #286, support useCallback with inputs
Browse files Browse the repository at this point in the history
  • Loading branch information
shadaj committed Aug 17, 2019
1 parent 959c47e commit 3dce67e
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# Changelog

## vNEXT
## Bug Fixes
+ Support `useCallback` with a function that takes arguments [PR #290](https://github.com/shadaj/slinky/pull/290)

## [v0.6.2](https://slinky.dev)
### Highlights :tada:
Expand Down
5 changes: 5 additions & 0 deletions core/src/main/scala/slinky/core/facade/React.scala
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@ private[slinky] object HooksRaw extends js.Object {
def useReducer[T, I, A](reducer: js.Function2[T, A, T], initialState: I, init: js.Function1[I, T]): js.Tuple2[T, js.Function1[A, Unit]] = js.native

def useCallback(callback: js.Function0[Unit], watchedObjects: js.Array[js.Any]): js.Function0[Unit] = js.native
def useCallback[T](callback: js.Function1[T, Unit], watchedObjects: js.Array[js.Any]): js.Function1[T, Unit] = js.native

def useMemo[T](callback: js.Function0[T], watchedObjects: js.Array[js.Any]): T = js.native

Expand Down Expand Up @@ -247,6 +248,10 @@ object Hooks {
HooksRaw.useCallback(callback, watchedObjects.toJSArray.asInstanceOf[js.Array[js.Any]])
}

@inline def useCallback[T](callback: T => Unit, watchedObjects: Iterable[Any]): T => Unit = {
HooksRaw.useCallback(callback, watchedObjects.toJSArray.asInstanceOf[js.Array[js.Any]])
}

@inline def useMemo[T](memoValue: () => T, watchedObjects: Iterable[Any]): T = {
HooksRaw.useMemo[T](memoValue, watchedObjects.toJSArray.asInstanceOf[js.Array[js.Any]])
}
Expand Down
23 changes: 23 additions & 0 deletions tests/src/test/scala/slinky/core/HooksComponentTest.scala
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,29 @@ class HooksComponentTest extends AsyncFunSuite {
assert(called)
}

test("useCallback with arguments produces callable function") {
val container = document.createElement("div")

var called = false

val component = FunctionalComponent[Unit] { props =>
val callback = useCallback((value: Boolean) => {
called = value
}, Seq.empty)

callback(true)

""
}

ReactDOM.render(
component(),
container
)

assert(called)
}

test("useMemo only recalculates when watched objects change") {
val container = document.createElement("div")

Expand Down

0 comments on commit 3dce67e

Please sign in to comment.