Caching JSON response using ETag in React Native app

What is the best way to implement the following script 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 user restarts the application.
  • Whenever this HTTP request is repeated, send an If-None-Match header.
    • When you get the "Not changed" response, use the version in the saved cache.
    • When you get the answer “Successful” (this means that the answer has been changed), discard the saved cache, save the new answer.

Does React Native have a component that does these things out of the box? If not, what is the most common way to use this?

+6
source share
3 answers

Phew Been more than a year. I suppose you know this loud no, right? You will need to analyze the response headers in order to capture the ETag and save it on the device (you are not using a browser), and then add the header to subsequent requests after extracting it from the storage engine of your choice.

I just found this because I was looking to see if anyone had seen this in React, not to mention React Native, and I can't see anything.

Little dragon, it's time to roll up your sleeves and come up with this thing ...

0
source

well, this is my current solution, not yet tested in production. would appreciate your feedback from google.

Axios, - , -unless, ! -

import api from 'your api wrapper.js'
api.etags = new Set;
api.cache = new Set;
api.addRequestTransform(request => {
  const etag = api.etags.get(request.url);
   if (etag) {
     request.headers['HTTP_IF_NONE_MATCH'] = etag;
   }
})

// or whatever you use to wrap ur HTT
api.addResponseTransform(response =>{ 
if (
    response.status === 304 &&
    response.headers &&
    response.headers.etag &&
    api.cache.has(response.headers.etag)
  ) {
    console.log('%cOVERRIDING 304', 'color:red;font-size:22px;');
    response.status = 200;
    response.data = api.cache.get(response.headers.etag);
  } else if (response.ok && response.headers && response.headers.etag) {
    api.cache.set(response.headers.etag, response.data);
    api.etags.set(response.config.url, response.headers.etag);
  }
});

api.cache etags api.etag, etag .

, , etags , . :)?

0

API fetch() React native http . 304, 200 .

:

https://github.com/heroku/react-refetch/issues/142

: fooobar.com/questions/16256858/...

React Natives API NSURLSession iOS okhttp3 Android. HTTP-. Cache-Control Expires HTTP. , , , .

: NSURLSession, , ?

, NSURLSession NSURLCache, , , , NSURLSession / , 200.

, NSURLSession , If-Modified-Since If-None-Match Last-Modified Etag ( ). ; , , . 304 ( ), NSURLSession 200 ( , , ).

0

Source: https://habr.com/ru/post/1676821/


All Articles