简体   繁体   English

将获取的 JSON 数据保存到 sessionStorage

[英]Save fetched JSON data to sessionStorage

I just figured out how to write an async/await function to fetch data from an API, and it's working, but it's hitting the API like crazy.我刚刚想出了如何编写一个 async/await function 来从 API 获取数据,它正在工作,但它像疯了一样击中 API。 So now I'm trying to save the fetched data to sessionStorage and only fetch from the API if the data isn't in the sessionStorage.所以现在我试图将获取的数据保存到 sessionStorage,并且如果数据不在 sessionStorage 中,则仅从 API 中获取。

Here's my code:这是我的代码:

const fetchMeetingData = async () => {
    console.log('api hit')
    try {
        const response = await fetch(https://sheet.best...)
        const data = await response.json()
        validate(data) // Clean data to remove null key values
        return data
    } catch (e) {
        console.log('Fetch error with getMeetingData()')
    }
}

const filterMeetings = async (filters) => {
    meetings = await fetchMeetingData()
    meetings.forEach((meeting) => {
        meeting.time2 = moment(meeting.time, ["h:mm A"]).format("HHmm")
    })
    let today = moment().format("dddd").toString()
    let hour = moment().format('HHmm').toString()
    let filteredMeetings = meetings.filter(function (matches) {
        if (document.querySelector('#select-day').selectedIndex === 0 && filters.searchText === '') {
            return matches.day === today &&
                moment(matches.time, ["h:mm A"]).format("HHmm") > hour
        } else {
            return true
        }
    })

Here's what I've tried:这是我尝试过的:

const fetchMeetingData = async () => {
    console.log('api hit')
    try {
        const response = await fetch(https://sheet.best...)
        const data = await response.json()
        validate(data) // Clean data to remove null key values
        sessionStorage.setItem('meetingData', JSON.stringify(data)) // added this line
        return data
    } catch (e) {
        console.log('Whoa! Fetch error with getMeetingData()')
    }
}

I'm not really sure where to go from here, or if this is even the correct approach.我不确定 go 从这里到哪里,或者这是否是正确的方法。 My noob instinct was to do something like this, which didn't work.我的菜鸟本能是做这样的事情,但没有奏效。

savedMeetingData = sessionStorage.getItem('meetingData')

const getSavedMeetingData = async () => {
    if (savedMeetingData) {
        meetings = savedMeetingData
        return meetings
    } else {
        fetchMeetingData()
        meetings = await data
        return meetings
    }

const filterMeetings = async (filters) => {
    meetings = await getSavedMeetingData() // replaces call to fetchMeetingData
    meetings.forEach((meeting) => {
        meeting.time2 = moment(meeting.time, ["h:mm A"]).format("HHmm")
    })

I'm not sure if that's exactly the code I was trying but it's close.我不确定这是否正是我正在尝试的代码,但它很接近。 The problem was the API was still getting hit, even though the data was stored successfully to sessionStorage.问题是 API 仍然受到攻击,即使数据已成功存储到 sessionStorage。

I'd really appreciate some help and/or suggestions on how to clarify this question.对于如何澄清这个问题,我真的很感激一些帮助和/或建议。

SOLUTION: Based on answer from @Christian解决方案:基于@Christian 的回答

// StackOverflow Q/A
async function getMeetingData() {
    const preLoadedData = sessionStorage.getItem('meetingData')
    if(!preLoadedData) {
        try {
            const response = await fetch('https://sheet.best...')
            const data = await response.json()
            validate(data)
            sessionStorage.setItem('meetingData', JSON.stringify(data))
            console.log('api hit')
            return data
        } catch (e) {
            console.log('Whoa! Fetch error with getMeetingData()')
        }
    } else {
        console.log('no api hit!!!')
        return JSON.parse(preLoadedData)
    }
}
async function getSavedMeetingData() {
    const meetings = await getMeetingData()
    return meetings
}
const filterMeetings = async (filters) => {
    meetings = await getSavedMeetingData()
    meetings.forEach((meeting) => {
        meeting.time2 = moment(meeting.time, ["h:mm A"]).format("HHmm")
    })

If you could be more explicit on what exactly did not work it would be great:) (did not save data in sessionStorage?, could not retrieve it?, etc...).如果您可以更明确地说明究竟是什么不起作用,那就太好了:)(没有在 sessionStorage 中保存数据?,无法检索它?等等...)。 Anyway, maybe you could try something like this and see if it helps:无论如何,也许你可以尝试这样的事情,看看它是否有帮助:

async function getSavedMeetingData() {
  const meetingData = await getMeetingData();
}

async function getMeetingData() {
  const preloadedData = sessionStorage.getItem('meetingData');

  if (!preloadedData) {
    try {
      const response = await fetch('https://myapiurl.com/');
      const data = validate(response.json());
      sessionStorage.setItem('meetingData', JSON.stringify(data));
      return data;
    } catch (e) {
      console.log('Whoa! Fetch error with getMeetingData()');
    }
  } else {
    return JSON.parse(preloadedData);
  }
}

One more reminder (just in case), keep in mind you are saving this to sessionStorage , so if you close the tab do not expect to have the information saved, in that case you should use localStorage .再提醒一下(以防万一),请记住您将其保存到sessionStorage ,因此如果您关闭选项卡,不要期望保存信息,在这种情况下您应该使用localStorage

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM