VueJS Gridsome Frontend API Caching Using LocalStorage Tutorial
Today I’m going to share a simple way to store/cache API data using LocalStorage. LocalStorage is a type of web storage that allows Javascript websites and apps to store and access data right in the browser with no expiration.
Table of Contents
Retrieve API Data Without Caching
In this article, I’ll use Axios
to get data from API. I hope you’ve an idea about Axios.
Install Axios:
npm i axios
Let’s get data without storing/caching:
<script>
import axios from "axios";
export default {
name: 'app',
data () {
return {
users: null
}
},
mounted () {
// load data from API
axios
.get('https://reqres.in/api/users?page=1')
.then(response => {
console.log(response.data.data)
this.users = response.data.data
})
.catch(error => console.log(error))
.finally(() => this.loading = false)
}
}
</script>
Retrieve API Data With Caching
To load our webpage quickly, we’re going to store/cache API data in local storage. Our app will check local data first. If data stored/cached in local, then the data will load from local otherwise the data will load from API.
Here’s the example of storing/caching API data using LocalStorage:
<script>
import axios from "axios";
export default {
name: 'app',
data () {
return {
users: null
}
},
mounted () {
let users_data = JSON.parse(localStorage.getItem('users_data'))
if (users_data) {
// load from local
this.users = users_data
}
else {
// load data from API
axios
.get('https://reqres.in/api/users?page=1')
.then(response => {
this.users = response.data.data
// store to local
localStorage.setItem('users_data', JSON.stringify(response.data.data));
})
.catch(error => console.log(error))
.finally(() => this.loading = false)
}
}
}
</script>
LocalStorage Methods
There are five methods of LocalStorage. I’m providing an example of each method.
setItem()
: Add key and value to localStorage.
Store a single value:
localStorage.setItem('name', 'MyNotePaper)
Store arrays or objects:
const user = {
name: "Test Name",
age: "25",
}
localStorage.setItem('user', JSON.stringify(user))
getItem()
: Retrieve a value by the key from localStorage.
Get a single value:
localStorage.getItem('name')
Get arrays or objects:
JSON.parse(window.localStorage.getItem('user'))
removeItem()
: Remove an item by key from localStorage.
localStorage.removeItem('name')
clear()
: Clear all localStorage.
localStorage.clear()
key()
: Passed a number to retrieve nth key of a localStorage.
var key = localStorage.key(index)
The article is over. Thanks for reading.
Md Obydullah
Software Engineer | Ethical Hacker & Cybersecurity...
Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.