Page Menu
Home
c4science
Search
Configure Global Search
Log In
Files
F123477809
useLocalStorage.js
No One
Temporary
Actions
Download File
Edit File
Delete File
View Transforms
Subscribe
Mute Notifications
Award Token
Subscribers
None
File Metadata
Details
File Info
Storage
Attached
Created
Sun, Jul 27, 17:08
Size
1 KB
Mime Type
text/x-java
Expires
Tue, Jul 29, 17:08 (1 d, 23 h)
Engine
blob
Format
Raw Data
Handle
27704584
Attached To
rOACCT Open Access Compliance Check Tool (OACCT)
useLocalStorage.js
View Options
import
React
from
'react'
;
var
getItem
=
function
getItem
(
key
)
{
try
{
var
itemValue
=
localStorage
.
getItem
(
key
);
if
(
typeof
itemValue
===
'string'
)
{
return
JSON
.
parse
(
itemValue
);
}
return
undefined
;
}
catch
(
_unused
)
{
return
undefined
;
}
};
export
default
function
useLocalStorage
(
key
,
defaultValue
)
{
var
_React$useState
=
React
.
useState
(),
value
=
_React$useState
[
0
],
setValue
=
_React$useState
[
1
];
React
.
useEffect
(
function
()
{
var
initialValue
=
getItem
(
key
);
if
(
typeof
initialValue
===
'undefined'
||
initialValue
===
null
)
{
setValue
(
typeof
defaultValue
===
'function'
?
defaultValue
()
:
defaultValue
);
}
else
{
setValue
(
initialValue
);
}
},
[
defaultValue
,
key
]);
var
setter
=
React
.
useCallback
(
function
(
updater
)
{
setValue
(
function
(
old
)
{
var
newVal
=
updater
;
if
(
typeof
updater
==
'function'
)
{
newVal
=
updater
(
old
);
}
try
{
localStorage
.
setItem
(
key
,
JSON
.
stringify
(
newVal
));
}
catch
(
_unused2
)
{}
return
newVal
;
});
},
[
key
]);
return
[
value
,
setter
];
}
Event Timeline
Log In to Comment