Search code examples
react-nativeasync-awaitasyncstorage

why my asyncstorage do not sync immediately


i want to have an immediate respond from asyncstorage when i set data but i cant seem to find a way here is my code

my listitem onpress => onLearnMore

onLearnMore = (rowData) => {
    this.setState({name:rowData.name}),
    this.setState({email:rowData.email}),
    this.setState({phone:rowData.phone}),
    this.setState({street:rowData.location.street}),
    this.setState({city:rowData.location.city}),
    this.setState({state:rowData.location.state}),
    this.setState({postcode:rowData.location.postcode}),
    this.saveData();
    //this.props.navigation.navigate('Details', { ...rowData });
  };

saveData to set item to asyncstorage

saveData(){
    let data = {
      name: this.state.name,
      email: this.state.email,
      phone: this.state.phone,
      street: this.state.street,
      city: this.state.city,
      state: this.state.state,
      postcode: this.state.postcode,
    }
    AsyncStorage.setItem('data',JSON.stringify(data));
    this.previewData();
  }

this is my previewData

  previewData = async () =>{
    try{
      let datachecker = await AsyncStorage.getItem('data');
      let parsed = JSON.parse(datachecker);
      alert(parsed.name);
    }catch(error){
      alert(error);
    }
  }

but the alert that show the item setted to asyncstorage do not sync immediately. i need to preview it twice to have the same result as setted state properties

update error case i figure out that when you set data to save into asyncstorage it can sync immediately, is there anyway to fix it?

i am sorry for broken english


Solution

  • setState is asynchronous in your first method onLearnMore you should batch all your update to one single setState and pass a callback to the second argument.

    onLearnMore = (rowData) => {
        this.setState({
          name: rowData.name,
          email: rowData.email,
          phone: rowData.phone,
          street: rowData.location.street,
          city: rowData.location.city,
          state: rowData.location.state,
          postcode: rowData.location.postcode
        }, () => {
         // setState second argument is a callback to be invoked
         // after updating state finished
         // this time you can now call any function that depends on the updated state
           this.saveData();
          //this.props.navigation.navigate('Details', { ...rowData })
        });
    
      };
    

    In your saveData function AsyncStorage.setItem is also asynchronous and returns a promise you could simply use .then or await but if you use await make sure to change the saveData function to async.

    using .then

    AsyncStorage.setItem('data',JSON.stringify(data)).then(this.previewData());
    

    or using await

    async saveData(){
        // omitted code
        await AsyncStorage.setItem('data',JSON.stringify(data));
        this.previewData();
      }