Here is my API code:
import axios from 'axios';
export const getAreaData = async (postcode) => {
const { data } = await axios.get(`/${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 , YouTube, Google, other methods.
I can't change this code too much, I need to add to it to store the response in cache.
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.
Share Improve this question edited Nov 14, 2023 at 13:59 Brian Tompsett - 汤莱恩 5,88372 gold badges61 silver badges133 bronze badges asked Jan 5, 2023 at 0:09 yos 24yos 24 931 gold badge1 silver badge3 bronze badges 1- If you are open to oher solutions besides Axios, I'd recommend something like React Query. – Chayapol Commented Jan 5, 2023 at 0:12
3 Answers
Reset to default 9A 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.
I may be late to awnser this, but be aware with patterns like the following:
// ---> DONT DO THIS <---
const cache = {};
async function request(url) {
if (cache[url]) {
return cache[url];
}
const data = await fetch(url);
cache[url] = data;
return data;
}
As they are the EASIEST way to have cache invalidation problems and are super hard to detect their bugs. I'd strongly recomend to use an already done axios caching library.
There are these two right now:
- https://axios-cache-interceptor.js.org/ (Newer, richer, faster and has 70k/weekly downloads, but you can ignore what I say because I'm the maintainer of it)
- https://github.com/RasCarlito/axios-cache-adapter (Deprecated, although still has more than 100k/weekly)
They integrate internally with axios and allows you to call axios.get(...)
infinitely times, resolving all requests, either from the cache or through a network request.
You can also try TanStack Query. It offers features such as caching, automatic refetching, background updates, and more. It supports Angular, React, Vue, Solid JS, and Svelte. Let's take a look at the following example for a React project. Please refer to their documentation for further details.
Here is how we can use it with axios:
// With Axios
const fetchUser = async (id) => {
const response = await axios.get(`/api/user/${id}`);
return response.data;
};
// With React Query
const fetchUser = async (id) => {
const response = await axios.get(`/api/user/${id}`);
return response.data;
};
const { data: user, isLoading, isError } = useQuery(["user", id], fetchUser);
Here is how we can use it with fetch:
const fetchUser = async () => {
const res = await fetch("/api/user");
if (!res.ok) {
throw new Error("Network response was not ok");
}
return res.json();
};
const UserInfo = () => {
const { data, status } = useQuery("user", fetchUser);
if (status === "loading") {
return <div>Loading...</div>;
}
if (status === "error") {
return <div>Error fetching data</div>;
}
return (
<div>
<h3>{data.name}</h3>
<p>{data.email}</p>
</div>
);
};
(Example Ref)