Skip to content

Instantly share code, notes, and snippets.

@troyscott
Created December 26, 2021 21:44
Show Gist options
  • Save troyscott/61e6028140d732beb394e888826b82e7 to your computer and use it in GitHub Desktop.
Save troyscott/61e6028140d732beb394e888826b82e7 to your computer and use it in GitHub Desktop.
Caching JSON Files with Axios
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Get Contacts Demo - Axios</title>
</head>
<body>
<h2>Contacts Caching Demo</h2>
<ul id="contacts">
</ul>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
/*
Caching Demo
This app assumes there is a file called contacts.json which is stored
in a folder called data. The file must contain an array of contacts with
first_name and last_name attributes:
[
{ "first_name": "Pat", "last_name": "Dibdall"}
]
Test Data: https://www.mockaroo.com
*/
console.log('caching demo ...');
// set the cache to time out in 30 seconds
const options = {
headers: {
'Cache-Control': 'max-age: 30'
}
};
axios.get('/data/contacts.json', options)
.then((response) => {
console.log('contacts data ...');
console.log('Check to see if the data has changed after 30 seonds')
lastModified = response.headers['last-modified'];
console.log('Last Modified:', lastModified);
console.log(response.data[0]);
firstName = response.data[0].first_name;
lastName = response.data[0].last_name;
fullName = firstName + ' ' + lastName;
console.log('First Name:', firstName);
const contactData = document.getElementById("contacts");
const listItem = document.createElement('li');
listItem.textContent = fullName + ' - ' + lastModified;
contactData.appendChild(listItem);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment