Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js cache http requests with axios

Tags:

vue.js

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?

like image 320
H. K. Avatar asked Apr 05 '18 11:04

H. K.


People also ask

Does axios cache requests?

You can allow axios-cache-adapter to cache the results of a request using (almost) any HTTP method by modifying the exclude.

How do I cache data in vue JS?

vue-server-renderer has built-in support for component-level caching. To enable it you need to provide a cache implementation when creating the renderer. Typical usage is passing in an lru-cache : const LRU = require('lru-cache') const renderer = createRenderer({ cache: LRU({ max: 10000, maxAge: ... }) })

Does axios work with vue?

Axios is a popular JavaScript library used to make HTTP requests. It is a promise-based HTTP client used in JavaScript or with other Javascript libraries like Vue. js or React.


1 Answers

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
like image 79
03balogun Avatar answered Sep 22 '22 09:09

03balogun