Search code examples
react-nativeasyncstorage

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!


Solution

  • 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");
    })