Search code examples
react-nativereact-native-navigation

AsyncStorage not fetching data first time


in my app i am storing a string in AsyncStrorage and it is storing but to retrive i have to go back one screen and come forward to the desired screen than it will fetch. below is mu code where i am fetching it.

let OccupancyType='';
export default class MonthlyAnalysis extends React.Component {   
      displayData = async ()=>{  
        try{  
          OccupancyType = await AsyncStorage.getItem('selectedOccupType');
        }  
        catch(error){  
          alert(error)  
        }  
      } 
  render(){
    this.displayData();
return(){

and code where i am storing is

AsyncStorage.setItem('selectedOccupType',selectedOccupType.toString());

for example i am storing on screen 1 and i need this in screen 3 and when i go to screen 3 it fetch nothing when i comback to screen 2 and then go forward to screen 3 it work. please help. thanks


Solution

  • call this.displayData() in componentDidMount and setState({OccupancyType: OccupancyType}) in displayData function.

     componentDidMount(){
        this.displayData();
        }
         displayData = async ()=>{  
            try{  
              OccupancyType = await 
          AsyncStorage.getItem('selectedOccupType');
          this.setState({OccupancyType:OccupancyType});
            }  
            catch(error){  
              alert(error)  
            }  
          } 
    

    then use this.state.OccupancyType