[Chartjs]-JavaScript & HTML – reusing data from fetch()

1πŸ‘

βœ…

You can tell a promise p to call multiple handlers when it’s available by calling p.then multiple times:

let data = fetch(url)
    .then(validateResponse)
    .then(readResponseAsJSON);

Promise.all([
  data.then(useDailyResult),
  data.then(buildAnotherChart)
]).catch(logError);

2πŸ‘

You can reuse the data fetched from the server if you just assign it to a variable your function has access to.

If you had another then in your chain that assigns to a var, then you can check that var before doing another fetch.

var remoteData = {}

function getDailyTranscripts (url) {
  // check for existing response data based on url param
  if(remoteData[url]) {
    console.log('using pre-fetched data from memory')
    useDailyResult(remoteData[url])
  }
  else {
    console.log('fetching from server', url)
    fetch(url)
      .then(validateResponse)
      .then(readResponseAsJSON)
      .then(jsonData => {
        // assuming readResponseAsJSON returns what you want
        remoteData[url] = jsonData
        useDailyResult(jsonData)
      })
      .catch(logError)
  }
}

Note that if you call getDailyTranscripts a second time while the initial fetch is still working, it will kick off another fetch. So you might want to add some logic to address that if it could be an issue for you.

It may just be best to (1) read remote data, then (2) pass it along that whatever is going to need it, if you know that ahead of time. But that just depends on your use case.

fetch(url)
  .then(validateResponse)
  .then(readResponseAsJSON)
  .then(handleAllYourChartsAtOnce) // this function could also store the json in a var
  .catch(logError)

Leave a comment