H. K.
H. K.

Reputation: 171

Vue.js cache http requests with axios

I'm developing a PWA with Vue.js. When the user starts it, some information from another application is needed. For this, i'm using axios:

let url = 'url';
axios.get(url).then((response) => {
  callback(response.data)
})

it's working fine as long as the user is online. if the network connection is OK, data should be retrieved by the URL, and if there is no internet connection, data should be loaded from cache. How is this possible?

Upvotes: 17

Views: 33595

Answers (1)

03balogun
03balogun

Reputation: 380

You can check out this extension https://github.com/kuitos/axios-extensions

Here is the basic usage example, I hope it helps

import axios from 'axios';
import { cacheAdapterEnhancer } from 'axios-extensions';

const http = axios.create({
    baseURL: '/',
    headers: { 'Cache-Control': 'no-cache' },
    // cache will be enabled by default
    adapter: cacheAdapterEnhancer(axios.defaults.adapter)
});

http.get('/users'); // make real http request
http.get('/users'); // use the response from the cache of previous request, without real http request made
http.get('/users', { cache: false }); // disable cache manually and the the real http request invoked

Upvotes: 20

Related Questions