Browse Source

caching data from user's pluviometer

master
analuizaff 3 years ago
parent
commit
453c83bcfe
  1. 8
      src/app/hooks/usePluviometricStation.js
  2. 43
      src/app/utility/cache.js

8
src/app/hooks/usePluviometricStation.js

@ -1,6 +1,7 @@
import { useState } from "react";
import getFieldsAnswers from "../api/RequestFieldsAnswers/getFieldsAnswers";
import webSocketClient from "../api/Websockets/webSocketClient";
import cache from "../utility/cache";
async function getPluvStation_data(id) {
const result = await getFieldsAnswers.fieldsAnswers(null, id);
@ -58,15 +59,18 @@ async function getPluviometerStation(userId, setPluviometerStation) {
pluvStation_data.data.responseData.array_to_json[0]
);
setPluviometerStation(pluvObject);
cache.store(socketObject, JSON.stringify(pluvObject))
} else {
setPluviometerStation(false);
cache.store(socketObject, false)
}
socketObject.close();
};
socketObject.onerror = (e) => {
socketObject.onerror = async (e) => {
const dataCache = await cache.get(url);
console.log(e.message);
setPluviometerStation(undefined);
setPluviometerStation(dataCache);
};
}

43
src/app/utility/cache.js

@ -0,0 +1,43 @@
import AsyncStorage from "@react-native-async-storage/async-storage";
import moment from "moment";
const prefix = "cache";
const expiryInMinutes = 5;
const store = async (key, value) => {
try {
const item = {
value,
timestamp: Date.now(),
};
await AsyncStorage.setItem(prefix + key, JSON.stringify(value));
} catch (error) {
console.log(error);
}
};
const isExpired = (intem) => {
const now = moment(Date.now());
const storedTime = moment(item.timestamp);
return now.diff(storedTime, "minutes") > expiryInMinutes;
};
const get = async(key) => {
try {
const value = await AsyncStorage.get(prefix + key);
if (!item) return null;
if (isExpired(isExperired)) {
await AsyncStorage.removeItem(prefix + key);
return null;
}
} catch (error) {
console.log(error);
}
};
export default {
store,
get,
};
Loading…
Cancel
Save