亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用本地存儲來存儲來自 API 的數據

如何使用本地存儲來存儲來自 API 的數據

BIG陽 2024-01-22 20:52:36
我只想偶爾從 API 獲取一次數據(例如每小時一次),并將其存儲在本地并在我的網站上使用該數據,而不必每次刷新瀏覽器時一次又一次地調用該 api。我們怎樣才能做到這一點。我們可以使用 localStorage 來實現這個目的嗎?如果是的話怎么辦?我正在使用這個:fetch("https://coronavirus-tracker-api.herokuapp.com/deaths").then(res=>{  return res.json();}).then(data=>{  localStorage.setItem("data",JSON.stringify(data));  console.log(localStorage.getItem("data"))})但這會在每次頁面重新加載時調用 api。但我不想一次又一次地調用 api,而是想將數據存儲在本地存儲中,并從那里獲取數據以在頁面上查看。
查看完整描述

1 回答

?
Smart貓小萌

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 中的過時數據檢查。


查看完整回答
反對 回復 2024-01-22
  • 1 回答
  • 0 關注
  • 200 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號