반응형
1. 세션스토리지에 정보와 만료시간 저장
function setWithExpiry(key, value, ttl) {
const now = new Date()
// `item` is an object which contains the original value
// as well as the time when it's supposed to expire
const item = {
value: value,
expiry: now.getTime() + ttl,
}
localStorage.setItem(key, JSON.stringify(item))
}
또는 다음과 같이 개별적으로 저장할 수 있다.
window.sessionStorage.setItem(key, value);
window.sessionStorage.setItem(key, expiry);
2. 스토리지에 저장된 정보 가져오기
스토리지에 저장된 정보를 조회하여 현재시간과 만료시간을 비교한다.
function getWithExpiry(key) {
const itemStr = localStorage.getItem(key)
// if the item doesn't exist, return null
if (!itemStr) {
return null
}
const item = JSON.parse(itemStr)
const now = new Date()
// compare the expiry time of the item with the current time
if (now.getTime() > item.expiry) {
// If the item is expired, delete the item from storage
// and return null
localStorage.removeItem(key)
return null
}
return item.value
}
반응형
'시사&트렌드 > 코딩' 카테고리의 다른 글
Objects are not valid as a React child 해결 방법 (0) | 2023.02.16 |
---|---|
TTL (Time To Live) (0) | 2023.02.16 |
자바스크립트 | 기본 문법 요약 (0) | 2023.02.16 |
리액트 & 클린코드 | 변수명 중복 피하기 (0) | 2023.02.16 |
리액트 | Props 사용할 때 주의사항 (0) | 2023.02.15 |