From 26e2bc8710df17ac9b16ad54b292ec127a0adff3 Mon Sep 17 00:00:00 2001 From: Tony Cuadra Date: Mon, 7 Oct 2024 18:05:26 -0700 Subject: [PATCH] Make table form of mapDispatchToProps work with callable table actionCreators --- src/connect.lua | 24 ++++++++++++++++-------- src/connect.spec.lua | 6 ++++++ 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/src/connect.lua b/src/connect.lua index 1b467b8..ad6abd7 100644 --- a/src/connect.lua +++ b/src/connect.lua @@ -32,6 +32,14 @@ local function noop() return nil end +--[[ + Returns `true` if the value can be called i.e. you can write `value(...)`. +]] +local function isCallable(value: any): boolean + return type(value) == "function" or + (type(value) == "table" and getmetatable(value) and getmetatable(value).__call ~= nil) or false +end + --[[ The stateUpdater accepts props when they update and computes the complete set of props that should be passed to the wrapped component. @@ -77,7 +85,7 @@ local function connect? ) if mapStateToPropsOrThunk ~= nil then - assert(typeof(mapStateToPropsOrThunk) == "function", "mapStateToProps must be a function or nil!") + assert(isCallable(mapStateToPropsOrThunk), "mapStateToProps must be a function or nil!") else mapStateToPropsOrThunk = noop end @@ -142,7 +150,7 @@ local function connect)( + (dispatch :: any) :: ThunkfulDispatchProp + ) + elseif mapDispatchType == "table" then mappedStoreDispatch = {} for key, actionCreator in pairs(mapDispatchToProps :: ActionCreatorMap) do - assert(typeof(actionCreator) == "function", "mapDispatchToProps must contain function values") + assert(isCallable(actionCreator), "mapDispatchToProps must contain function values") mappedStoreDispatch[key] = function(...) dispatch(actionCreator(...)) end end - elseif mapDispatchType == "function" then - mappedStoreDispatch = (mapDispatchToProps :: MapDispatchToProps)( - (dispatch :: any) :: ThunkfulDispatchProp - ) end local stateUpdater = makeStateUpdater(self.store) diff --git a/src/connect.spec.lua b/src/connect.spec.lua index e0c1628..ee0fb6d 100644 --- a/src/connect.spec.lua +++ b/src/connect.spec.lua @@ -53,6 +53,12 @@ return function() }) end) + it("should accept action creators that are callable tables", function() + connect(nil, { + foo = Rodux.makeActionCreator("Foo", function() end), + }) + end) + it("should throw if not passed a component", function() local selector = function(store) return {}