Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JavaScript Axios/Fetch. Can you disable browser cache?

I am trying to query a quote API for a freeCodeCamp project I'm updating to React.js. I am now trying to use Fetch or Axios to query the API but it's caching the response in the browser. I know in $ajax there is a { cache: false } that would force the browser to do a new request.

Is there some way I will be able to do the same with Fetch or Axios?

The cache-control setting seems to be already set to max-age: 0 by Axios.

enter image description here

This is my code I have that is querying the API.

generateQuote = () => {   axios.get('https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1')     .then(response => {       const { title, content, link } = response.data[0];       console.log(title, content, link)       this.setState(() => ({ title, content, link }));     })     .catch(err => {       console.log(`${err} whilst contacting the quote API.`)     }) 

}

like image 715
Asjas Avatar asked Mar 13 '18 18:03

Asjas


People also ask

How do I disable Axios cache?

To disable browser cache with JavaScript Axios, we can set the Cache-control and Pragma request headers to no-cache . And we set the Expires request header to 0. to disable caching the response.

Does Axios use cache?

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

How do I turn off caching in react?

To clear browser cache in React, we can add meta tags inside the head tag to make sure that the content of the page isn't cached. in the head tag to set the cache-control response reader to no-cache . And the expires response header is set to 0 to make sure nothing is cached.


1 Answers

Okay so I found a solution. I had to set a timestamp on the API url to get it to make a new call. There doesn't seem to be a way to force axios or fetch to disable cache.

This is how my code now looks

axios.get(`https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&timestamp=${new Date().getTime()}`)   .then(response => {     const { title, content, link } = response.data[0];     console.log(title, content, link)     this.setState(() => ({ title, content, link }));   })   .catch(err => {     console.log(`${err} whilst contacting the quote API.`)   }) 
like image 62
Asjas Avatar answered Sep 21 '22 02:09

Asjas