Skip to content
This repository has been archived by the owner on Dec 13, 2023. It is now read-only.

Allow functions to be passed to setState #39

Merged
Merged
Show file tree
Hide file tree
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
5 changes: 5 additions & 0 deletions lib/Component.lua
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,11 @@ function Component:setState(partialState)
error(INVALID_SETSTATE_MESSAGE, 0)
end

-- If the partial state is a function, invoke it to get the actual partial state.
if type(partialState) == "function" then
partialState = partialState(self.state, self.props)
end

local newState = {}

for key, value in pairs(self.state) do
Expand Down
45 changes: 45 additions & 0 deletions lib/Component.spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -326,5 +326,50 @@ return function()

Reconciler.teardown(instance)
end)

it("should invoke functions to compute a partial state", function()
local TestComponent = Component:extend("TestComponent")
local setStateCallback, getStateCallback, getPropsCallback

function TestComponent:init()
setStateCallback = function(newState)
self:setState(newState)
end

getStateCallback = function()
return self.state
end

getPropsCallback = function()
return self.props
end

self.state = {
value = 0
}
end

function TestComponent:render()
return nil
end

local element = Core.createElement(TestComponent)
local instance = Reconciler.reify(element)

expect(getStateCallback().value).to.equal(0)

setStateCallback(function(state, props)
expect(state).to.equal(getStateCallback())
expect(props).to.equal(getPropsCallback())

return {
value = state.value + 1
}
end)

expect(getStateCallback().value).to.equal(1)

Reconciler.teardown(instance)
end)
end)
end