Shubham Bhattacharya
Shubham Bhattacharya

Reputation: 100

Async storage data load time

I am using Asyncstorage to store user data like:

try {
      await AsyncStorage.setItem(prod_id, '1').then(()=>{
        alert('Added to Cart');
      });
    } catch (error) {
      console.log(error);
    }

but when I add it to onPress action it takes long time to save data and then my alert is called. Am I doing something wrong? Please I need help!

Upvotes: 0

Views: 2049

Answers (1)

Mohammed Ashfaq
Mohammed Ashfaq

Reputation: 3426

I think you are mixing two ways of handling the promises in JS.

  1. Using Async await
async function SetItem(){
  try {
    await AsyncStorage.setItem(prod_id, '1')
    alert('Added to Cart');
  } catch (error) {
    console.log(error);
  }
}
  1. with then and catch
function SetItem(){
  return AsyncStorage.setItem(prod_id, '1')
  .then(()=>{
    alert('Added to Cart');
  }).catch((error)=> {
    console.log(error)
  })
}

calling this method

this.SetItem().then(()=>{
 console.log("value is set");
})

Upvotes: 1

Related Questions