Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native fetch API cannot disable caching

I am building android app using react native expo integrated with redux. The API is called using fetch method, but always the cached result is displayed. The server did not receive the request second time. I tried disabling cache with the following code.

export const mymails = (token) => {
    return fetch(
        API_URL+'?random_number='+ new Date().getTime(), {
        method: 'GET',
        headers: getHeaders(token)
    })  
    .then(response => response.json());
};

getHeaders = (token) => {
    return {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Authorization': 'Token token='+token,
        'Cache-Control': 'no-cache, no-store, must-revalidate',
        'Pragma': 'no-cache',
        'Expires': 0
    };
}

When I call the API through Postman client I see different result(not cached). I tried adding random number as parameter and setting cache control headers, but still returning cached result. Is there is anything else I could try.

Thanks

like image 282
Mirza Vu Avatar asked Dec 07 '17 17:12

Mirza Vu


1 Answers

There must be a problem with how are you setting up the headers for fetching request.

Try with following,

You can follow the link for the same in the Official Fetch API

const mymails = (token) => {

    var myHeaders = new Headers();
    myHeaders.set('Accept', 'application/json');
    myHeaders.set('Content-Type', 'application/json');
    myHeaders.set('Authorization', 'Token token=' + String(token));
    myHeaders.set('Cache-Control', 'no-cache');
    myHeaders.set('Pragma', 'no-cache');
    myHeaders.set('Expires', '0');

    return fetch(
        API_URL + '?random_number=' + new Date().getTime(), {
            method: 'GET',
            headers: myHeaders
        })
        .then(response => response.json());
};
like image 63
RAHUL JOSHI Avatar answered Sep 24 '22 10:09

RAHUL JOSHI