Home > Blockchain >  How do I cache an API axios response
How do I cache an API axios response

Time:01-06

Here is my api code:

import axios from 'axios';


export const getAreaData = async (postcode) => {
    const { data } = await axios.get(`https://api.zippopotam.us/GB/${postcode}`);
    return data.places;
};

This api call returns an array of objects. I need to store it in cache to improve performance, how can I do that?

Tried https://www.npmjs.com/package/axios-cache-adapter youtube google other methods

I can't change this code too much, i need to add to it to store the response in cache.

CodePudding user response:

A cache is essentially a local store of data. You can save the response to your query for the rest of the program runtime, assuming it's not permanently online (i.e. it's not a server). From the perspective of the code calling the function, ideally it shouldn't know or care whether the data is cached or not (this is called having a transparent cache).

import axios from 'axios';

// store data here
const areaDataCache = {};

export const getAreaData = async (postcode) => {
  // if cache doesn't contain data
  if (!areaDataCache[postcode]) {
    // load data and add it to cache
    const { data } = await axios.get(`https://api.zippopotam.us/GB/${postcode}`);
    areaDataCache[postcode] = data.places
  }
  // cached data
  return areaDataCache[postcode];
};

This is the simplest implementation possible, and doesn't have any more advanced concepts in it like setting an expiry date for data, which would force it to be fetched again after a set amount of time has passed, or alternatively clearing out the entire cache after a certain length of time/a certain number of requests.

  • Related