{"id":12080,"library":"storage-utility","title":"Storage Utility","description":"This `storage-utility` package, currently at version 3.1.3, provides a unified and persistent key-value storage solution for both web environments (using `localStorage` by default) and React Native applications (integrating with `AsyncStorage`). It aims to simplify cross-platform storage management. Since its 2.0.0 release, it supports time-based data expiration, allowing developers to store values with a defined lifespan, similar to HTTP cookies. A key feature introduced in version 3.0.0 is the transition to promise-based getter functions, primarily addressed through `GetItemAsync`, to robustly handle the asynchronous nature of storage engines like `AsyncStorage` and prevent race conditions encountered in earlier synchronous approaches. Additionally, the library offers a unique categorization of data into 'volatile' and 'nonVolatile' sets, enabling targeted data cleanup operations, such as clearing all user-specific 'volatile' data upon logout. It has an active release cycle, with significant updates in major versions focusing on stability, performance, and expanded functionality. Its core differentiator lies in its dual-platform support and advanced storage policies like time-based invalidation and data categorization.","status":"active","version":"3.1.3","language":"javascript","source_language":"en","source_url":"https://github.com/drivezy/storage-utility","tags":["javascript","storage","localstorage","asyncStorage"],"install":[{"cmd":"npm install storage-utility","lang":"bash","label":"npm"},{"cmd":"yarn add storage-utility","lang":"bash","label":"yarn"},{"cmd":"pnpm add storage-utility","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required for React Native projects when using AsyncStorage as the storage engine.","package":"@react-native-async-storage/async-storage","optional":true}],"imports":[{"note":"Primarily for React Native setup. Optional for web unless overriding defaults.","wrong":"const InitializeStorageUtils = require('storage-utility').InitializeStorageUtils;","symbol":"InitializeStorageUtils","correct":"import { InitializeStorageUtils } from 'storage-utility';"},{"note":"This is a named export. Ensure to destructure correctly.","wrong":"import SetItem from 'storage-utility';","symbol":"SetItem","correct":"import { SetItem } from 'storage-utility';"},{"note":"Introduced in v3.0.0 as the primary promise-based getter, especially for AsyncStorage.","wrong":"const GetItemAsync = require('storage-utility').GetItemAsync;","symbol":"GetItemAsync","correct":"import { GetItemAsync } from 'storage-utility';"},{"note":"While `GetItem` still exists, `GetItemAsync` should be preferred for consistency and when interacting with asynchronous engines like AsyncStorage since v3.0.0. `GetItem` might return a Promise if configured with an async engine.","wrong":"await GetItem('key'); // If used for AsyncStorage without await in v3+","symbol":"GetItem","correct":"import { GetItem } from 'storage-utility';"}],"quickstart":{"code":"import React, { useEffect, useState } from 'react';\nimport { GetItemAsync, SetItem, InitializeStorageUtils } from 'storage-utility';\nimport AsyncStorage from '@react-native-async-storage/async-storage'; // Ensure this is installed for RN\n\n// This setup would typically be in your app's entry point or root component constructor\n// For a browser environment, InitializeStorageUtils can often be skipped.\nInitializeStorageUtils({\n    storeName: 'MyTestStore',\n    engine: AsyncStorage, // Use localStorage for web: window.localStorage\n    engineName: 'AsyncStorage' // Use 'localStorage' for web\n});\n\nconst StorageExample = () => {\n    const [value, setValue] = useState(null);\n    const key = 'myPersistentData';\n\n    useEffect(() => {\n        const storeAndRetrieve = async () => {\n            console.log('Attempting to set item...');\n            // Store data that expires in 1 minute and is volatile\n            SetItem(key, { message: 'Hello from storage!', timestamp: Date.now() }, { span: 1, isNonVolatile: false });\n            console.log('Item set. Waiting for retrieval...');\n\n            // Retrieve the data using the async getter\n            const stored = await GetItemAsync(key);\n            setValue(stored);\n            console.log('Retrieved:', stored);\n        };\n\n        storeAndRetrieve();\n    }, []);\n\n    return (\n        <div>\n            <h1>Storage Utility Example</h1>\n            <p>Stored Value: {value ? JSON.stringify(value) : 'No value found or expired'}</p>\n            <p>Check console for logs.</p>\n        </div>\n    );\n};\n\nexport default StorageExample;","lang":"typescript","description":"Demonstrates initializing `storage-utility` for React Native (or browser), setting a time-sensitive item, and asynchronously retrieving it."},"warnings":[{"fix":"Always use `await GetItemAsync('key')` for retrieving values, especially when using AsyncStorage or in contexts where values might be fetched asynchronously. If using `GetItem`, be aware it might return a Promise and should be awaited.","message":"With v3.0.0, getter functions became promise-based, primarily manifesting through the introduction of `GetItemAsync`. The `GetItem` function itself might now return a Promise if configured with an asynchronous engine like AsyncStorage, which is a breaking change from its previous synchronous behavior.","severity":"breaking","affected_versions":">=3.0.0"},{"fix":"Call `InitializeStorageUtils({ engine: AsyncStorage, engineName: 'AsyncStorage' })` once at the root of your React Native application or component. For web, it can be skipped unless you need to override the default `localStorage` engine or `storeName`.","message":"The `InitializeStorageUtils` function is critical for setting up the environment in React Native with `AsyncStorage`. Failing to call it with the correct `engine` and `engineName` will lead to runtime errors when attempting to use storage functions.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Review `SetItem` calls and update to `SetItem(key, payload, { span: <minutes>, isNonVolatile: false })` if time-based expiration or non-volatile categorization is intended.","message":"Version 2.0.0 introduced time-based storage policy via the `span` option in `SetItem`. While a feature, it changed the `SetItem` API signature by adding an options object, meaning older direct calls without the options object might behave differently or need adjustment if `span` functionality is desired.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"For data that should not be automatically purged by volatile cleanup mechanisms, explicitly set `isNonVolatile: true` in the options object: `SetItem(key, payload, { isNonVolatile: true })`.","message":"Data stored using `SetItem` without `isNonVolatile: true` is considered 'volatile' and can be mass-deleted by specific utility functions not detailed in the provided API. If data must persist across specific actions (like user logout), ensure it's marked as non-volatile.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Ensure `InitializeStorageUtils` is called at application startup with a valid storage engine. For React Native, this means `InitializeStorageUtils({ engine: AsyncStorage, engineName: 'AsyncStorage' });` after importing `AsyncStorage`.","cause":"The `InitializeStorageUtils` function was not called or was called with an invalid `engine` object, especially common in React Native where `AsyncStorage` needs to be provided.","error":"TypeError: Cannot read properties of undefined (reading 'getItem')"},{"fix":"Always `await` the result of `GetItemAsync('key')`. If using `GetItem` and encountering this, switch to `GetItemAsync` or ensure `await` is applied if `GetItem` is configured with an async engine.","cause":"Attempting to use `GetItem` or `GetItemAsync` (post v3.0.0) in an asynchronous context (like React Native's AsyncStorage) without `await`.","error":"Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'then') OR GetItem returns Promise {<pending>}"},{"fix":"Install `@react-native-async-storage/async-storage` (`npm install @react-native-async-storage/async-storage`) and `import AsyncStorage from '@react-native-async-storage/async-storage';` in your React Native files.","cause":"You are attempting to use `AsyncStorage` in React Native but have not imported it or installed the necessary package (`@react-native-async-storage/async-storage`).","error":"ReferenceError: AsyncStorage is not defined"}],"ecosystem":"npm"}