1 回答

TA貢獻1911條經驗 獲得超7個贊
這實際上取決于您要存儲的數據量。通常,當您需要處理少量數據時,您更喜歡使用 localStorage。
另一種選擇也是可能的,它是 IndexedDB,它更兼容并且允許您存儲更多數據。
但是如果你想竊取使用 localStorage,那么你可以在獲取數據之前檢查是否使用了密鑰存儲“數據”:
const data = localStorage.getItem('data');
if (!data) {
?// then fetch your data
}
請注意,localStorage 始終存儲鍵值對,并且值始終是字符串。因此,如果您想在檢索值時處理它,請不要忘記JSON.parse(data)
編輯:重新打開選項卡時刷新過時的數據
要每 3-4 小時更新一次數據,您可以存儲獲取數據的日期。您需要更新一點,但對承諾結果中的響應的處理:
const getDataFromLocalStorage = () => {
? const dataStringified = localStorage.getItem('data');
? return data && JSON.parse(dataStringified) || null;
};
const areDataOutdated = (receivedAt) => {
? ? if (!dataReceivedAt || isNaN(Date.parse(receivedAt)) {
? ? ? ?return true;
? ? }
? ? // Basically, we take the actual date, and we removed 4 hours
? ? const checkDate = new Date(new Date().getTime() - (60 * 60 * 4 * 1000));
? ? // If the data received is lower than the checkDate, it means that data are outdated.
? ? return new Date(receivedAt).getTime() < checkDate.getTime();
};
const data = getDataFromLocalStorage();
if (!data || areDataOutdated(data && data.receivedAt)) {
? ?// then fetch your data
? ?fetch("https://coronavirus-tracker-api.herokuapp.com/deaths")
? ? ?.then(res=> {
? ? ? ?// instead of storing directly your response, construct a object that will store also the date
? ? ? ?localStorage.setItem("data", JSON.stringify({response: res.json(), receivedAt: new Date()}));
? ? ? ?console.log(localStorage.getItem("data"))
? ? ?})
}
編輯2:停留在頁面上時刷新數據
const getDataFromLocalStorage = () => {
? const dataStringified = localStorage.getItem('data');
? return data && JSON.parse(dataStringified) || null;
};
const fetchData = () => {
? fetch("https://coronavirus-tracker-api.herokuapp.com/deaths")
? ? ?.then(res=> {
? ? ? ?// instead of storing directly your response, construct a object that will store also the date
? ? ? ?localStorage.setItem("data", JSON.stringify({response: res.json(), receivedAt: new Date()}));
? ? ? ?console.log(localStorage.getItem("data"))
? ? ?})
}
setInterval(() => {
? ?fetchData();
}, 1000 * 60 * 60 * 4) // every 4 hours, we'll fetch the data.
const data = getDataFromLocalStorage();
if (!data) {
? ?fetchData();
}
但您也可以結合編輯 1 中的過時數據檢查。
- 1 回答
- 0 關注
- 200 瀏覽
添加回答
舉報