...
const [recentKeyword, setRecentKeyword] = useState(
JSON.parse(localStorage.getItem('recentkeyword') || '[]')
);
...
const checkMaximumRecentSearch = (): boolean => {
const MAXIMUM_SIZE = 10;
return recentKeyword.length > MAXIMUM_SIZE;
};
useEffect(() => {
const newRecentKeyword = checkMaximumRecentSearch()
? [...recentKeyword.slice(0, -1)]
: recentKeyword;
localStorage.setItem('recentKeyword', JSON.stringify(newRecentKeyword));
setRecentKeyword(newRecentKeyword);
}, [recentKeyword]);
...
const loadedRecentKeyword = localStorage.getItem('recentKeyword')
? JSON.parse(localStorage.getItem('recentKeyword')!)
: [];
const [recentKeyword, setRecentKeyword] = useState(loadedRecentKeyword);
...
const checkMaximumRecentSearch = (): boolean => {
const MAXIMUM_SIZE = 10;
return recentKeyword.length > MAXIMUM_SIZE;
};
useEffect(() => {
const newRecentKeyword = checkMaximumRecentSearch()
? [...recentKeyword.slice(0, -1)]
: recentKeyword;
window.localStorage.setItem(
'recentKeyword',
JSON.stringify(newRecentKeyword)
);
setRecentKeyword(newRecentKeyword);
}, [recentKeyword]);
참고 사이트
stackoverflow - localStorage is saving my data but after refresh is reseting and empty it