From 3dce67eb1a242124145b5572accca6c105560be7 Mon Sep 17 00:00:00 2001 From: Shadaj Laddad Date: Sat, 17 Aug 2019 12:07:48 -0700 Subject: [PATCH] Fix #286, support useCallback with inputs --- CHANGELOG.md | 2 ++ .../main/scala/slinky/core/facade/React.scala | 5 ++++ .../slinky/core/HooksComponentTest.scala | 23 +++++++++++++++++++ 3 files changed, 30 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d4797e19..03aff9e8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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: diff --git a/core/src/main/scala/slinky/core/facade/React.scala b/core/src/main/scala/slinky/core/facade/React.scala index 86adce2f..45c5bab9 100644 --- a/core/src/main/scala/slinky/core/facade/React.scala +++ b/core/src/main/scala/slinky/core/facade/React.scala @@ -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 @@ -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]]) } diff --git a/tests/src/test/scala/slinky/core/HooksComponentTest.scala b/tests/src/test/scala/slinky/core/HooksComponentTest.scala index c2002d55..128383fa 100644 --- a/tests/src/test/scala/slinky/core/HooksComponentTest.scala +++ b/tests/src/test/scala/slinky/core/HooksComponentTest.scala @@ -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")