GabrielTrettel
3 years ago
3 changed files with 52 additions and 6 deletions
@ -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, |
|||
}; |
Write
Preview
Loading…
Cancel
Save
Reference in new issue