Skip to content
GitLab
Projects
Groups
Snippets
/
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in
Toggle navigation
Menu
Open sidebar
Rex Dri
Rex Dri
Commits
407f7253
Verified
Commit
407f7253
authored
Apr 11, 2020
by
Florent Chehab
Browse files
fix(useSharedState): kind of safer
parent
3ea4525d
Changes
1
Hide whitespace changes
Inline
Side-by-side
frontend/src/hooks/useSharedState.js
View file @
407f7253
import
{
useCallback
,
useEffect
,
useState
}
from
"
react
"
;
import
{
useCallback
,
useEffect
,
useMemo
,
useRef
,
useState
}
from
"
react
"
;
import
usePersistentState
,
{
getPersistedValue
}
from
"
./usePersistentState
"
;
import
useConstantState
from
"
./useConstantState
"
;
...
...
@@ -23,8 +23,17 @@ function useSharedState(key, valueIfNoPrevious) {
// A bit of optimization in order no to save to the persisted state every time
const
[
state
,
setState
]
=
useState
(
persistedState
);
// hack with useConstantState to make sure it is run NOW
useConstantState
(()
=>
{
useEffect
(()
=>
{
return
()
=>
{
// Cleaning listeners list on unmount
if
(
listenersByKey
.
has
(
key
))
{
listenersByKey
.
get
(
key
).
delete
(
setState
);
}
};
},
[]);
// hack with useMemo to make sure it is run NOW
useMemo
(()
=>
{
// Subscribe as a listener
if
(
!
listenersByKey
.
has
(
key
))
listenersByKey
.
set
(
key
,
new
Set
());
listenersByKey
.
get
(
key
).
add
(
setState
);
...
...
@@ -32,13 +41,6 @@ function useSharedState(key, valueIfNoPrevious) {
// small check to make sure the value is coherent
const
valueInStore
=
getPersistedValue
(
key
);
if
(
valueInStore
!==
state
)
setState
(
valueInStore
);
});
useEffect
(()
=>
{
return
()
=>
{
// Cleaning listeners list on unmount
listenersByKey
.
get
(
key
).
delete
(
setState
);
};
},
[]);
const
setStateOut
=
useCallback
(
...
...
Write
Preview
Supports
Markdown
0%
Try again
or
attach a new file
.
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment