Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save Multiple Key Values using react-native-keychain?

I have multiple key, value and I dont know how can I store multiple key, value in different places.

Is there an alternative way for the following code using react-native-keychain package ??

await AsyncStorage.setItem('pincode',  '12345');
await AsyncStorage.setItem('userid',  '@user8383928');
await AsyncStorage.setItem('contacts',  JSON.stringify(contacts_array_of_object));

Every above key, value saving may called in different functions and in a different time.

Problem is in react-native-keychain there is only two property username, password:

async () => {
  const username = 'zuck';
  const password = 'poniesRgr8';

  // Store the credentials
  await Keychain.setGenericPassword(username, password);

  try {
    // Retrieve the credentials
    const credentials = await Keychain.getGenericPassword();
    if (credentials) {
      console.log('Credentials successfully loaded for user ' + credentials.username);
    } else {
      console.log('No credentials stored');
    }
  } catch (error) {
    console.log('Keychain couldn\'t be accessed!', error);
  }
  await Keychain.resetGenericPassword();
}
like image 232
Muhammad Avatar asked Feb 22 '20 13:02

Muhammad


2 Answers

1) setInternetCredentials

setInternetCredentials(server, username, password) accepts server as first parameter. Server can be any string.

await setInternetCredentials('pincode', 'pincode', '123456');
await setInternetCredentials('contacts', 'contacts', JSON.stringify(contacts_array_of_object));

You can then get it from keychain using

await getInternetCredentials('pincode');

2) setGenericPassword with service value

setGenericPassword(username, password, [{ accessControl, accessible, accessGroup, service, securityLevel }]) You have to specify service value, which is the name used for storing secret in internal storage

await setGenericPassword('pincode', '123456', [{ service = 'pincode' }]);

3) JSON.strigify with setGenericPassword

Every time you would want to write something you would read keystore first and use object spread to store it back together with a new value.

like image 55
Black Avatar answered Sep 21 '22 12:09

Black


put them all in one object and then save it as JSON.stringify({...})

like image 45
Belqis Avatar answered Sep 19 '22 12:09

Belqis