typed-async-storage
A tiny wrapper for AsyncStorage that allows creating schema-based storage and validation using PropTypes
Installation
npm install --save typed-async-storage
Usage
Import the package along with AsyncStorage and PropTypes
;;;
Simple storage
To create a simple storage (single storage) use your old friend PropTypes to create a schema
const simpleSchema = greetingText: PropTypesstringisRequired darkMode: PropTypesboolisRequired;
Call createStorage and pass these required params: storage name, schema, and AsyncStorage
const simpleStorage = ;
Now you can interact with your 'simpleStorage' and have PropTypes validation out of the box!
await simpleStorage;const isDarkMode = await simpleStorage;console; // prints 'true' await simpleStorage;// TypeError: Invalid property `greetingText` of type `number` supplied to `simpleStorage`, expected `string`.
Multiple Storage
To deal with sets you have to wrap your schema in PropTypes.objectOf(). Refer to the below example:
// Or you can use PropTypes.objectOf(PropTypes.shape({ ... }))const usersSchema = PropTypes; const usersStorage = ; await usersStorage; // pass an array of keys you want to getawait usersStorage;
Note
To make things simple, try to create storages that are as small as possible. For each group of items, create a new storage (users, settings, channels, etc.). Do not create a master storage that contains all the data of your application, it is impossible to deal with it using this package. Break it down into several smaller storages.
API
API is built over AsyncStorage API
Simple Storage
// Sets value for a specific key // Gets value for a specific key // Merges an existing value stored under 'key', with new 'value' // Check how it works: https://react-native-community.github.io/async-storage/docs/api#mergeitem // Removes all data for myKey1 // Returns all keys for a specific storage // Removes all data for all keys in a specific storage
Multiple Storage
// Sets values for specific keys // Gets values for specific keys // Multiple merging of existing and new values in a batch // Removes all data for key1 and key2 // Returns all keys for a specific storage // Removes all data for all keys in a specific storage
Contributing
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
Please make sure to update tests as appropriate.