Amazon Developer

as

Settings
Sign out
Notifications
Alexa
Amazon Appstore
Ring
AWS
Documentation
Support
Contact Us
My Cases
Get Started
Design and Develop
Publish
Reference
Support

🚧 AsyncStorageWithKeyScope

AsyncStorageWithKeyScope is an abstraction built on top of AsyncStorage for Vega. It implements the same API with some restrictions: It adds a clearScope() method to be used instead of the clear() method and Vega's removeValuesForKeysWithPrefix() method.

AsyncStorage is an unencrypted, asynchronous, persistent, key-value storage system that is global to the app. It should be used instead of LocalStorage.

AsyncStorageWithKeyScope allows you to create instances with a scope prefix string you define. The instance will then transparently prepend all keys with that scope prefix followed by an _ when you make calls to the instance's APIs and remove the prepended prefix and underscore when returning results.

The AsyncStorageWithKeyScope JavaScript code is a facade that provides a clear JavaScript API, real Error objects, and non-multi functions. Each method in the API returns a Promise object.

Importing the AsyncStorageWithKeyScope library:


import {AsyncStorageWithKeyScope} from '@amazon-devices/react-native-kepler';

Persisting data:

Copied to clipboard.


const scopedAsyncStore = new AsyncStorageWithKeyScope("MyAppVideoSettings");

_storeData = async () => {
  try {
    await scopedAsyncStore.setItem(
      'description',
      'I like to save it.',
    );
  } catch (error) {
    // Error saving data
  }
};

Fetching data:

Copied to clipboard.


const scopedAsyncStore = new AsyncStorageWithKeyScope("MyAppVideoSettings");

_retrieveData = async () => {
  try {
    const value = await scopedAsyncStore.getItem('description');
    if (value !== null) {
      // We have data!!
      console.log(value);
    }
  } catch (error) {
    // Error retrieving data
  }
};


Reference

Methods

constructor()


constructor(scopePrefix)

Constructs a AsyncStorageWithKeyScope instance with a designated scope prefix string.

Parameters:

Name Type Required Description
scopePrefix string Yes A non empty string to transparently prefix store keys with

getItem()


getItem(key: string, [callback]: ?(error: ?Error, result: ?string) => void)

Fetches an item for a key and invokes a callback upon completion. Returns a Promise object.

Parameters:

Name Type Required Description
key string Yes Key of the item to fetch.
callback ?(error: ?Error, result: ?string) => void No Function that will be called with a result if found or any error.

setItem()


setItem(key: string, value: string, [callback]: ?(error: ?Error) => void)

Sets the value for a key and invokes a callback upon completion. Returns a Promise object.

Note: Ensure your keys are determinate or you may not be able to get or remove them later. Keys with timestamps or other variable information may be difficult to identify later and could result in wasted storage.

Parameters:

Name Type Required Description
key string Yes Key of the item to set.
value string Yes Value to set for the key.
callback ?(error: ?Error) => void No Function that will be called with any error.

removeItem()


removeItem(key: string, [callback]: ?(error: ?Error) => void)

Removes an item for a key and invokes a callback upon completion. Returns a Promise object.

Parameters:

Name Type Required Description
key string Yes Key of the item to remove.
callback ?(error: ?Error) => void No Function that will be called with any error.

mergeItem() Vega Not Available


mergeItem(key: string, value: string, [callback]: ?(error: ?Error) => void)

Merges an existing key value with an input value, assuming both values are stringified JSON. Returns a Promise object.

NOTE: This is not supported by all native implementations.

Parameters:

Name Type Required Description
key string Yes Key of the item to modify.
value string Yes New value to merge for the key.
callback ?(error: ?Error) => void No Function that will be called with any error.

Example:

Copied to clipboard.


const scopedAsyncStore = new AsyncStorageWithKeyScope("MyAppUserSettings");

let UID123_object = {
  name: 'Chris',
  age: 30,
  traits: {hair: 'brown', eyes: 'brown'},
};
// You only need to define what will be added or updated
let UID123_delta = {
  age: 31,
  traits: {eyes: 'blue', shoe_size: 10},
};

scopedAsyncStore.setItem(
  'UID123',
  JSON.stringify(UID123_object),
  () => {
    scopedAsyncStore.mergeItem(
      'UID123',
      JSON.stringify(UID123_delta),
      () => {
        scopedAsyncStore.getItem('UID123', (err, result) => {
          console.log(result);
        });
      },
    );
  },
);

// Console log result:
// => {'name':'Chris','age':31,'traits':
//    {'shoe_size':10,'hair':'brown','eyes':'blue'}}


clear() Vega Not Available


clear([callback]: ?(error: ?Error) => void)

This method is not supported in AsyncStorageWithKeyScope. Use clearScope instead.

If you want to erase all data in the store use AsyncStorage.clear() directly. It is generally not recommended to clear data for scopes you don't own.

Parameters:

Name Type Required Description
callback ?(error: ?Error) => void No Function that will be called with any error.

clearScope()


clearScope([callback]: ?(error: ?Error) => void)

Remove all values in the store whose keys are prefixed with the scope prefix + '_'.

Parameters:

Name Type Required Description
callback ?(error: ?Error) => void No Function that will be called with any error.

getAllKeys() Vega Not Available


getAllKeys([callback]: ?(error: ?Error, keys: ?Array<string>) => void)

Gets all keys known to your app; for all callers, libraries, etc. Returns a Promise object.

Parameters:

Name Type Required Description
callback ?(error: ?Error, keys: ?Array<string>) => void No Function that will be called with all keys found and any error.

multiGet()


multiGet(keys: Array<string>, [callback]: ?(errors: ?Array<Error>, result: ?Array<Array<string>>) => void)

This allows you to batch the fetching of items given an array of key inputs. Your callback will be invoked with an array of corresponding key-value pairs found:


multiGet(['k1', 'k2'], cb) -> cb([['k1', 'val1'], ['k2', 'val2']])

The method returns a Promise object.

Parameters:

Name Type Required Description
keys Array<string> Yes Array of key for the items to get.
callback ?(errors: ?Array<Error>, result: ?Array<Array<string>>) => void No Function that will be called with a key-value array of the results, plus an array of any key-specific errors found.

Example:

Copied to clipboard.


const scopedAsyncStore = new AsyncStorageWithKeyScope("MyAppUserSettings");

const keys = ['key1', 'key2', 'key3'];
scopedAsyncStore.multiGet(keys, (err, stores) => {
	stores.map((result, i, store) => {
		// get at each store's key/value so you can work with it
		let key = store[i][0];
		let value = store[i][1];
	});
});


multiSet()


multiSet(keyValuePairs: Array<Array<string>>, [callback]: ?(errors: ?Array<Error>) => void)

Use this as a batch operation for storing multiple key-value pairs. When the operation completes you'll get a single callback with any errors.

Note: Ensure your keys are determinate or you may not be able to get or remove them later. Keys with timestamps or other variable information may be difficult to identify later and could result in wasted storage.


multiSet([['k1', 'val1'], ['k2', 'val2']], cb);

The method returns a Promise object.

Parameters:

Name Type Required Description
keyValuePairs Array<Array<string>> Yes Array of key-value array for the items to set.
callback ?(errors: ?Array<Error>) => void No Function that will be called with an array of any key-specific errors found.

multiRemove()


multiRemove(keys: Array<string>, [callback]: ?(errors: ?Array<Error>) => void)

Call this to batch the deletion of all keys in the keys array. Returns a Promise object.

Parameters:

Name Type Required Description
keys Array<string> Yes Array of key for the items to delete.
callback ?(errors: ?Array<Error>) => void No Function that will be called an array of any key-specific errors found.

Example:

Copied to clipboard.


const scopedAsyncStore = new AsyncStorageWithKeyScope("MyAppUserSettings");

let keys = ['k1', 'k2'];
scopedAsyncStore.multiRemove(keys, err => {
  // keys k1 & k2 removed, if they existed
  // do most stuff after removal (if you want)
});


removeValuesForKeysWithPrefix() Vega Not Available


removeValuesForKeysWithPrefix(prefix: string, [callback]: ?(errors: ?Array<Error>) => void)

This method will return an error if called on an AsyncStorageWithKeyScope instance. Use clearScope() instead.

Parameters:

Name Type Required Description
prefix string Yes Prefix to match against keys for items to remove. Must not be empty.
callback ?(errors: ?Array<Error>) => void No Function that will be called an array of any key-specific errors found.

multiMerge() Vega Not Available


multiMerge(keyValuePairs: Array<Array<string>>, [callback]: ?(errors: ?Array<Error>) => void)

Batch operation to merge in existing and new values for a given set of keys. This assumes that the values are stringified JSON. Returns a Promise object.

NOTE: This is not supported by all native implementations.

Parameters:

Name Type Required Description
keyValuePairs Array<Array<string>> Yes Array of key-value array for the items to merge.
callback ?(errors: ?Array<Error>) => void No Function that will be called with an array of any key-specific errors found.

Example:

Copied to clipboard.


const scopedAsyncStore = new AsyncStorageWithKeyScope("MyAppUserSettings");

// first user, initial values
let UID234_object = {
    name: 'Chris',
    age: 30,
    traits: {hair: 'brown', eyes: 'brown'},
};

// first user, delta values
let UID234_delta = {
    age: 31,
    traits: {eyes: 'blue', shoe_size: 10},
};

// second user, initial values
let UID345_object = {
    name: 'Marge',
    age: 25,
    traits: {hair: 'blonde', eyes: 'blue'},
};

// second user, delta values
let UID345_delta = {
    age: 26,
    traits: {eyes: 'green', shoe_size: 6},
};

let multi_set_pairs = [
    ['UID234', JSON.stringify(UID234_object)],
    ['UID345', JSON.stringify(UID345_object)],
];
let multi_merge_pairs = [
    ['UID234', JSON.stringify(UID234_delta)],
    ['UID345', JSON.stringify(UID345_delta)],
];


scopedAsyncStore.multiSet(multi_set_pairs, err => {
    scopedAsyncStore.multiMerge(multi_merge_pairs, err => {
        scopedAsyncStore.multiGet(['UID234', 'UID345'], (err, stores) => {
            stores.map((result, i, store) => {
                let key = store[i][0];
                let val = store[i][1];
                console.log(key, val);
            });
        });
    });
});

// Console log results:
// => UID234 {"name":"Chris","age":31,"traits":{"shoe_size":10,"hair":"brown","eyes":"blue"}}
// => UID345 {"name":"Marge","age":26,"traits":{"shoe_size":6,"hair":"blonde","eyes":"green"}}


Last updated: May 13, 2026