Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the React Native fetch() API support caching?

My app uses fetch(uri, { cache: 'default' }) to query a server and logs the response headers to the console. When my app fetches with the same URI a second and subsequent times, I would expect to see a status 304, but it continues to respond with 200, even though the response has a cache-control header with a max-age of 86400 (1 day).

I noticed that the server is using Cloudfare and cf-cache-status is set to "HIT" meaning that it is serving from a CDN, but I wouldn't expect that to stop the fetch API from caching.

Do I need to implement my own custom caching solution if I want to avoid re-fetching the same data more than once?

like image 614
Lawrence I. Siden Avatar asked Jun 23 '26 08:06

Lawrence I. Siden


1 Answers

It would not be great to rely on the statusCodes of the api's returned.

Since fetch considers statusCodes 101, 204, 205, or 304 as null body status as mentioned here

There are many parameters and steps involved to set the statusCode as 304, for a cache-fetch response which needs to be inspected throughly.

But the main thing to note is

Fetch will inspect the HTTP cache on the way to the network. If there is a fresh response it will be used. If there is a stale response a conditional request will be created, and a normal request otherwise. It then updates the HTTP cache with the response.

Therefore you can check for the following tags If-Modified-Since, If-None-Match, If-Unmodified-Since, If-Match, or If-Range, if they are set then it will automatically set the cache mode to nostore

like image 199
Pritish Vaidya Avatar answered Jun 28 '26 02:06

Pritish Vaidya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!