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 2 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.props, self.state)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's flip-flop the arguments to match React. I think most cases of functional setState are going to depend on state more than props anyhow.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense; fixed now!

end

local newState = {}

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

Reconciler.teardown(instance)
end)

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

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

getStateCallback = function()
return self.state
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(props, state)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We might want to assert which argument is which in this function to guard against them being the wrong tables!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done!

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

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

Reconciler.teardown(instance)
end)
end)
end