How to Implement Caching with Local Storage using Axios?

Fri Apr 14 2023

4 min read

Caching is an essential technique used in modern web applications to improve performance and reduce the number of API requests made by the client.

Axios is a popular HTTP client library for JavaScript that provides built-in caching capabilities.

However, the built-in cache mechanism in Axios has its limitations and may not always meet the needs of your application. This is where caching with local storage comes in handy.

Axios and local storage

Axios is a popular HTTP client library for JavaScript that provides an easy-to-use interface for making API requests. It supports a wide range of request methods, including GET, POST, PUT, DELETE, and more.

When making API requests, it's common to receive the same data multiple times. This can lead to slow loading times and an increase in the number of requests made by the client. Caching is a technique used to store data that has already been retrieved so that subsequent requests can be served from a local cache instead of making a new request to the server.

Local storage is an excellent option for caching data in the client's browser. When a request is made, the response can be stored in local storage with a unique key that can be used to retrieve the data later. You can read more about API caching here.

Storing cached data in local storage

To store data in local storage, you can use the setItem() method of the localStorage object. This method accepts two arguments: a key and a value. The key is a string that uniquely identifies the data, while the value can be any valid JavaScript object.

Before storing the data, it's important to format it appropriately. Local storage can only store strings, so you'll need to serialize the data into a string format, such as JSON.

Here's an example of how to store cached data in local storage:

js
const data = { id: 1, name: "John Doe" };
const key = "cachedData";
const value = JSON.stringify(data);
localStorage.setItem(key, value);

Cache a get request using localstorage

For this example, we will be using the Famous Quotes API from Rapid API Hub. To use this API, you will need to sign up for a Rapid API account and subscribe to the Famous Quotes API. Once you have subscribed to the API, you will be able to call the API from your Rapid API key.

Loading component...

We’ll first check if there is any cached data stored in the browser's local storage. If cached data exists, the code uses it instead of making a new request to the API. Otherwise, it makes a new request to the API and caches the response in the local storage.

html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Example</title>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
<script>
// Check if there is cached data in local storage
const cachedData = localStorage.getItem('cachedData');
if (cachedData) {
// Use the cached data instead of making a new request
const data = JSON.parse(cachedData);
console.log('Using cached data:', data);
} else {
// Make a new request and cache the response
axios.get('https://famous-quotes4.p.rapidapi.com/random', {
params: {category: 'all', count: '2'},
headers: {
'X-RapidAPI-Key': 'your-api-key',
'X-RapidAPI-Host': 'famous-quotes4.p.rapidapi.com'
}
})
.then(response => {
// Save the response data to local storage
localStorage.setItem('cachedData', JSON.stringify(response.data));
console.log('New data:', response.data);
})
.catch(error => {
console.error(error);
});
}
</script>
</body>
</html>

Wrap up

Caching with local storage is a powerful technique for improving performance and reducing the number of API requests made by the client. It involves storing response data from API requests in the client's browser, which can subsequently be served from the local cache instead of making a new request to the server.

However, it's important to keep in mind that local storage has its limitations, including storage capacity and security risks. Nonetheless, with careful use and consideration, caching with local storage can be a useful tool for optimizing your web application.