UNPKG

@shaaz1000/rn-storage

Version:

A comprehensive storage solution for React Native with encryption, caching, and offline sync

106 lines 3.46 kB
"use strict"; // src/hooks/useStorage.ts var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.useStorage = void 0; const react_1 = require("react"); const storageManager_1 = __importDefault(require("../core/storageManager")); const offlineSync_1 = __importDefault(require("../core/offlineSync")); const cacheManager_1 = __importDefault(require("../core/cacheManager")); function useStorage(key, initialValue, options = {}) { const [value, setValue] = (0, react_1.useState)(initialValue); const [loading, setLoading] = (0, react_1.useState)(true); const [error, setError] = (0, react_1.useState)(null); const storage = storageManager_1.default.getInstance(); const cache = cacheManager_1.default.getInstance(); const offlineSync = offlineSync_1.default.getInstance(); // Load initial value (0, react_1.useEffect)(() => { const loadValue = async () => { try { setLoading(true); let storedValue = null; if (options.cache) { storedValue = await cache.get(key); } if (!storedValue) { storedValue = await storage.getItem(key, options.encrypt); } if (storedValue !== null) { setValue(storedValue); } } catch (err) { setError(err); } finally { setLoading(false); } }; loadValue(); }, [key]); // Update value const updateValue = (0, react_1.useCallback)(async (newValue) => { try { setLoading(true); if (options.cache) { await cache.set(key, newValue, options.expiryTime); } await storage.setItem(key, newValue, options.encrypt, options.expiryTime); if (options.sync) { await offlineSync.queueOperation({ key, value: newValue, operation: 'set', timestamp: Date.now() }); } setValue(newValue); setError(null); } catch (err) { setError(err); } finally { setLoading(false); } }, [key, options]); // Remove value const removeValue = (0, react_1.useCallback)(async () => { try { setLoading(true); if (options.cache) { await cache.remove(key); } await storage.removeItem(key); if (options.sync) { await offlineSync.queueOperation({ key, value: null, operation: 'remove', timestamp: Date.now() }); } setValue(initialValue); setError(null); } catch (err) { setError(err); } finally { setLoading(false); } }, [key, options]); return { value, setValue: updateValue, remove: removeValue, loading, error, }; } exports.useStorage = useStorage; exports.default = useStorage; //# sourceMappingURL=useStorage.js.map