score:4

Accepted answer

here is a localstorage wrapper i wrote not so long ago, it also includes the functionality to set ttl on an object/key if you need an expiration date behavior, i use it for the same logic as you do, which is to check if there is a saved token and navigate to the main app view instead of the login page.

here is the wrapper:

// rn < 0.59
import { asyncstorage } from 'react-native'
// rn > 0.59
import asyncstorage from '@react-native-community/async-storage';


/**
 *
 * @param key key value of the object to be saved
 * @param object the object to save
 * @param ttl (optional) set an expiration date on an object in ms
 * @return {promise<void>}
 */
export const setobjectforkey = async ({key, object, ttl = undefined }) => {

    if (!key) throw new error('cannot set an object without a key');

    if (!object) throw new error('cannot set a key without an object');

    let expiresat = undefined;
    if (ttl) {
        expiresat = new date().gettime() + ttl;
    }
    let wrappedobj = {
        object,
        expiresat,
    };
    let stringedwrapper = json.stringify(wrappedobj);

    return await asyncstorage.setitem(key,stringedwrapper)
};


/**
 *
 * @param key the key of the object to remove
 * @return {promise<void>}
 */
export const removeobjectforkey = async (key) => {
    return await asyncstorage.removeitem(key)
};


/**
 *
 * @param key the key of the object to retrieve
 * @return {promise<*>}
 */
export const getobjectforkey = async (key) => {
    let now = new date().gettime();
    let stringedwrapper = await asyncstorage.getitem(key);

    if (!stringedwrapper) throw new error('no key found for object');

    let wrapper = json.parse(stringedwrapper);
    if (wrapper.expiresat < now) {
        // object expired
        asyncstorage.removeitem(key);
        throw new error('object expired');
    } else {
        return wrapper.object;
    }
};

and here is a usage example (in my solution i have a redux middleware so after i retrieve an object i call dispatch):

get:

let key = 'app_token';
localstorage.getobjectforkey(key)
            .then((retrievedobject) => {
               // do what you want with object
            })
            .catch((err) => {
               // handle error, object either doesn't exist, expired or a system error
            })

set:

 let key = 'app_token';
 let object = {token: 'jwt_hash'};
 let ttl = undefinded // ttl is optional
 localstorage.setobjectforkey({
            key,
            object,
            ttl,
        })
            .then(() => {
               // set was successfull
            })
            .catch((err) => {
                // handle error
            })

delete:

localstorage.removeobjectforkey(key)
            .then(() => {
              // successfully deleted
            })
            .catch((err) => {
               // object either doesn't exist to delete or system error
            })

notice that i actually save objects that i stringify, so even if i'm save the api token, i actaully save an object with a token as a key, i.e: {token: 'token'}

hope that helps

update 2019-06-06

as of react-native 0.59, the asyncstorage module is deprecated due to the efforts to make react-native's core library thinner... the asyncstorage should now be installed through @react-native-community/react-native-async-storage

score:2

 /* login screen */

async storesessiontoken(token) {
  try {
    await asyncstorage.setitem('token', token);
    console.log("data saved successfully");
    // rest of your code
  } catch (error) {
    console.log("error while storing the token");
  }
}




/* splash screen  */ 

async retrievesessiontoken() {
  try {
    const token = await asyncstorage.getitem('token');
    if (token !== null) {
      console.log("session token",token );
      return token;
    }
   } catch (error) {
     console.log("error while storing the token");
   }
}



// calling retrievesessiontoken
componentdidmount() {
  this.retrievesessiontoken()
  .then((token)=> { 
    if(token) this.setstate({token: token})
  })
}


Related Query

More Query from same tag