This repository has been archived by the owner on Jan 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
useSelector.lua
80 lines (69 loc) · 1.87 KB
/
useSelector.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
local HookConnection = require(script.Parent.Parent.HookConnection)
local function defaultEqualityCheck(a, b)
return a == b
end
--[=[
Allows you to extract data from the store state, using a selector function.
:::warning
Selectors should be [pure](https://en.wikipedia.org/wiki/Pure_function) since they are potentially executed multiple times and at arbitrary points in time.
:::
@function useSelector
@within Hooks
@tag roact-rodux
@tag rodux
@param selector (state: S) -> R
@param equalityFn ((a: any, b: any) -> boolean) | nil
@return HookCreator<R>
]=]
local function useSelector(roselect, useStore)
local createSelectorCreator = roselect.createSelectorCreator
local defaultMemoize = roselect.defaultMemoize
return function(selector, equalityFn)
return function(hooks)
local checkEqual = hooks.useMemo(function()
if not equalityFn then
equalityFn = defaultEqualityCheck
end
return equalityFn
end, { equalityFn })
local store = useStore(hooks)
local state = store:getState()
local _, setState = hooks.useState(state)
hooks.useEffect(function()
local hookConnection = store[HookConnection]
if hookConnection == nil then
store[HookConnection] = {
connection = store.changed:connect(function(newState)
setState(newState)
end),
hookCount = 1,
}
else
hookConnection.hookCount += 1
end
return function()
if hookConnection then
hookConnection.hookCount -= 1
if hookConnection.hookCount == 0 then
hookConnection.connection:disconnect()
store[HookConnection] = nil
end
end
end
end, {})
local result = hooks.useMemo(function()
return createSelectorCreator(
defaultMemoize,
checkEqual
)(
function()
return state
end,
selector
)()
end, { state })
return result
end
end
end
return useSelector