Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

how to cache data in javascript

//For example when we have a function responsible for retrieving 
//and returning data we can use a strategy 
//called memoization to retrieve data from the cache 
//if it was already fetched before:

const axios = require('axios')

let fetchCount = 0

function memoize(fn) {
  const cache = {}

  return async function (key, ...args) {
    if (cache[key]) {
      return cache[key]
    }

    fetchCount++
    return (cache[key] = await fn(...args))
  }
}

const fetchDogs = memoize(function (page) {
  if (typeof page !== 'number') page = 1
  return axios
    .get(
      `https://dog.ceo/api/breeds/list/all
    `,
    )
    .then((response) => {
      return response.data.message
    })
    .catch((err) => {
      throw err
    })
})

async function start() {
  try {
    let dogs = await fetchDogs(`dogs_page_11`, 11)
    return dogs
  } catch (error) {
    const err = error instanceof Error ? error : new Error(String(error))
    console.error(`Error: ${err.message}`, err)
  }
}
Comment

PREVIOUS NEXT
Code Example
Javascript :: ignore eslint warning one line 
Javascript :: getcomputedstyle 
Javascript :: javascript easiest way to get second parent 
Javascript :: javascript two digits number 
Javascript :: electron check if file exists 
Javascript :: javascript log html element as dom object 
Javascript :: javascript consecutive numbers in array 
Javascript :: Material-ui add alert icon 
Javascript :: On pressing enter change the focus to the next input field 
Javascript :: manifest.json basic structure 
Javascript :: custom event js 
Javascript :: javascript indexof 
Javascript :: javascript if browser out of focus 
Javascript :: how to read breakline in html 
Javascript :: json data sample 
Javascript :: convert to 24 hours format javasript 
Javascript :: nodejs sha512 decrypt 
Javascript :: javascript change color of text input 
Javascript :: why is my mongoose middleware not working 
Javascript :: laravel json response with error code 
Javascript :: react native navigation navigate 
Javascript :: redis nodejs 
Javascript :: deep merge nested objects javascript 
Javascript :: pushing element in array in javascript 
Javascript :: sequelize order with include 
Javascript :: react native apk bundle 
Javascript :: scss next js 
Javascript :: javascript collection to array 
Javascript :: time js code 
Javascript :: aos initial configuration vue 
ADD CONTENT
Topic
Content
Source link
Name
8+6 =