Caching a JSON response using ETag in a React Native app
caching, etag, http, react-native
Solution
The fetch() API of React native is following the http caching spec and it provides this feature. When you hit a 304 a 200 old response will be found in the cache and be reused.
Details:
https://github.com/heroku/react-refetch/issues/142
As answered at: https://stackoverflow.com/a/51905151
React Native’s fetch API bridges to NSURLSession on iOS and okhttp3 on Android. Both of these libraries strictly follow the HTTP caching spec. The caching behavior will depend primarily on the Cache-Control and Expires headers in the HTTP response. Each of these libraries have their own configuration you can adjust, for example to control the cache size or to disable caching.
And this: How to use NSURLSession to determine if resource has changed?
The caching provided by NSURLSession via NSURLCache is transparent, meaning when you request a previously cached resource NSURLSession will call the completion handlers/delegates as if a 200 response occurred.
If the cached response has expired then NSURLSession will send a new request to the origin server, but will include the If-Modified-Since and If-None-Match headers using the Last-Modified and Etag entity headers in the cached (though expired) result; this behavior is built in, you don't have to do anything besides enable caching. If the origin server returns a 304 (Not Modified), then NSURLSession will transform this to a 200 response the application (making it look like you fetched a new copy of the resource, even though it was still served from the cache).
Problem
What is the best way to implement the following scenario in a React Native app? - Make an HTTP request to the server, get a JSON response and an ETag header. - Save this JSON response in a way that will persist even after the app is restarted by the user. - Whenever this HTTP request is repeated, send an If-None-Match header. - When you get a "Not Modified" response, use the version in the persisted cache. - When you get a "Successful" response (meaning the response has changed), invalidate the persisted cache, save the new response. Does React Native have a component that does these things out of the box? If not, what is the most common way people use to handle this?