GithubHelp home page GithubHelp logo

artxty / typed-async-storage Goto Github PK

View Code? Open in Web Editor NEW
8.0 2.0 13.0 246 KB

Validate your AsyncStorage using PropTypes!

License: MIT License

JavaScript 100.00%
react react-native asyncstorage asyncstorage-wrapper proptype-validators storage

typed-async-storage's Introduction

Build

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

import createStorage from 'typed-async-storage';
import AsyncStorage from '@react-native-community/async-storage';
import PropTypes from 'prop-types';

Simple storage

To create a simple storage (single storage) use your old friend PropTypes to create a schema

const simpleSchema = {
  greetingText: PropTypes.string.isRequired,
  darkMode: PropTypes.bool.isRequired,
};

Call createStorage and pass these required params: storage name, schema, and AsyncStorage

const simpleStorage = createStorage({
  name: 'simpleStorage', // name must be unique for every storage
  schema: simpleSchema,
  AsyncStorage,
});

Now you can interact with your 'simpleStorage' and have PropTypes validation out of the box!

await simpleStorage.set('darkMode', true);
const isDarkMode = await simpleStorage.get('darkMode');
console.log(isDarkMode); // prints 'true'

await simpleStorage.set('greetingText', 42);
// 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.objectOf(PropTypes.exact({
  name: PropTypes.string.isRequired,
  address: PropTypes.string.isRequired,
  birthDate: PropTypes.instanceOf(Date).isRequired,
}));

const usersStorage = createStorage({
  name: 'usersStorage',
  schema: usersSchema,
  AsyncStorage,
  isMultiple: true, // pass 'true' to a create multiple storage
});

await usersStorage.set({ // pass an object {key: data, ...} of items
  user1: {
    name: 'Bob',
    address: '42 12th Street',
    birthDate: new Date(2020, 1, 1),
  },
  user2: {
    name: 'Mike',
    address: '1 Main Street',
    birthDate: new Date(2019, 1, 1),
  },
});

// pass an array of keys you want to get
await usersStorage.get(['user1', 'user2']);

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
set('myKey1', { a: 1, b: 'text' })

// Gets value for a specific key
get('myKey1')

// Merges an existing value stored under 'key', with new 'value'
merge('myKey1', { b: 'test' }) // Check how it works: https://react-native-community.github.io/async-storage/docs/api#mergeitem

// Removes all data for myKey1
remove('myKey1')

// Returns all keys for a specific storage
getAllKeys()

// Removes all data for all keys in a specific storage
clear()

Multiple Storage

// Sets values for specific keys
set({
  key1: { a: 1, b: 'string' },
  key2: { a: 2, b: 'string1' },
})

// Gets values for specific keys
get(['key1', 'key2'])

// Multiple merging of existing and new values in a batch
merge({
  key1: { a: 5,},
  key2: { b: 'str' },
})

// Removes all data for key1 and key2
remove(['key1', 'key2'])

// Returns all keys for a specific storage
getAllKeys()

// Removes all data for all keys in a specific storage
clear()

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.

License

MIT

typed-async-storage's People

Contributors

artxty avatar conjurer2306 avatar dependabot[bot] avatar mrshoopa avatar siddharthborderwala avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

typed-async-storage's Issues

Bug: TypeError occurs in expo production mode

Describe the bug
Getting TypeError: Failed property type: STORAGE_NAME: property type 'PROPERTY' is invalid; it must be a function, usually from the `prop-types` package, but received 'function'. when starting an expo app in production mode

Expected behavior
No error

TODO:

  • removeItem
  • mergeItem
  • getAllKeys
  • multiMerge
  • multiRemove
  • clear

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.