Search code examples
reactjsreact-nativeuse-stateasyncstorage

AsyncStorage not storing data and subsequently does not retrieve data


I am using expo and react-native I am trying to use AsyncStorage to save 3 values in persistent storage so I can get it from anywhere in the app, but asyncstorage is not saving or retrieving,

I have rewritten the code several times and several diffrent ways and have tried a few tutorials, nothing works,

so here is the code for the page where i save the data (Login.js)

import React, { useState} from 'react'
import { View, Text,TextInput ,Button,SafeAreaView,Image,} from 'react-native'

import { ProgressDialog,Dialog } from 'react-native-simple-dialogs';

import AsyncStorage from '@react-native-community/async-storage';


import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'
 
 

function Login ({navigation}){
 
  
  const[alerted,isalerted]=useState(false)
  const[authError,setAuthError]=useState(false)
  const[accInactive,isAccInactive]=useState(false)
  const[loginFail,didLoginFail]=useState(false)
  const[login,didLogin]=useState(false)
  const[email,setemail]=useState(email)
  const[ClientID,setClientID]=useState(ClientID)
  const[Password,setPassword]=useState(Password)
 
 

Here I am Trying to set the items for Asyncstorage

  function LoginButton () {
    AsyncStorage.setItem("MyEmail",email)
  AsyncStorage.setItem("MyPassword",Password)
  AsyncStorage.setItem("MyClientID",ClientID)

    fetch('https://www.SITE.co.za/app-login.asp?ClientID='+ClientID+'&Username='+email+'&Pwd='+Password)
    .then((response) => response.json())
    .then((responseJson) => {
      //Successful response from the API Call
      
     
      if (JSON.stringify(responseJson).includes("Login Success")){
      
        {isalerted(true),didLogin(false),isLoggedIn('Yes')}
        
     
    
      
       
      }
    else if (JSON.stringify(responseJson).includes("No Authentication Details Received"))
    {
     {setAuthError(true)}
  
    }
   else  if (JSON.stringify(responseJson).includes("Account Not Active"))
    {
     {isAccInactive(true)}
  
    }
  else  if (JSON.stringify(responseJson).includes("Login Details Incorrect"))
    {
      {didLoginFail(true)}
  
    }
     
    })
    .catch((error) => {
      console.error(error);
    });
  }
  
  function navButton(){
   
 
   
    navigation.navigate('Dashboard')
    isalerted(false)
  }

     return (
        <KeyboardAwareScrollView keyboardShouldPersistTaps='handled'>
<SafeAreaView>
<ProgressDialog
    visible={didLogin}
    activityIndicatorColor="#4994CF"
    activityIndicatorSize="large"
    animationType="slide"
    title="Logging in"
    message="Please, wait..."
/>

<Dialog
    visible={alerted}
    
    onTouchOutside={''} >
    <View>
      <Text style={{color:'green',fontSize:20, marginBottom:10 ,textAlign:"center"}}>Login Success</Text>
      <Button
      title="Continue To Dashboard"
      onPress={navButton}
      />
       
    </View>
</Dialog>
 <Dialog
    visible={authError}
    
    onTouchOutside={''} >
    <View>
      <Text style={{color:'red',fontSize:20, marginBottom:10 ,textAlign:"center"}}>No Authentication Details Received</Text>
      <Button
      title="OK"
      onPress={ ()=>setAuthError(false)}
      />
       
    </View>
</Dialog>
<Dialog
    visible={accInactive}
    
    onTouchOutside={''} >
    <View>
      <Text style={{color:'red',fontSize:20, marginBottom:10 ,textAlign:"center"}}>Account Not Active</Text>
      <Button
      title="OK"
      onPress={ () =>isAccInactive(false)}
      />
       
    </View>
</Dialog>
<Dialog
    visible={loginFail}
    
    onTouchOutside={''} >
    <View>
      <Text style={{color:'red',fontSize:20, marginBottom:10 ,textAlign:"center"}}>Login Details Incorrect</Text>
      <Button
      title="OK"
      onPress={()=> didLoginFail(false)}
      />
       
    </View>
</Dialog> 


<View style={{flexDirection:"row"}}>
        <Image source={{uri: 'https://www.SITEe.co.za/images/smartpractice-logo-02.png'}}
       style={{marginTop:35,paddingTop:10
      , height: 80,width:360,flexWrap:'wrap',resizeMode:"contain" }} /> 
<Text style={{textAlign:'center',color:"#4994CF", marginTop:35}}>Beta</Text>
</View>
<View style={{width:'95%',alignContent:'center',marginLeft:10}}>
  <Text style={{fontSize:20,color:'grey'}}>Welcome to the SmartPractice Beta App,
    Please Login below with your SmartPractice login Details
  </Text>
</View>

        <View style={{marginTop:10,alignItems:"center"}}>
          <View style={styles.Label}>
          
        <Text style={styles.LabelText}>Email</Text>
        </View>
          <TextInput onChangeText={(text)=>setemail(text)} autoCompleteType='email' placeholder="Email"   style={{width:'95%',height:40,backgroundColor:'#d8d8d8',marginBottom:3, paddingHorizontal: 10,marginTop:5}}/>
          <View style={styles.Label}>
        <Text style={styles.LabelText}>Password</Text>
        </View>
          <TextInput onChangeText={(text)=>setPassword(text)} autoCompleteType="password" secureTextEntry={true} placeholder="Password"   style={{width:'95%',height:40,backgroundColor:'#d8d8d8',marginBottom:3, paddingHorizontal: 10,marginTop:5}}/>
          <View style={styles.Label}>
          <Text style={styles.LabelText}>ClientID</Text>
         </View>
          <TextInput onChangeText={(text)=>setClientID(text)} keyboardType="numeric" placeholder="ClientID"  style={{width:'95%',height:40,backgroundColor:'#d8d8d8',marginBottom:3, paddingHorizontal: 10,marginTop:5}}/>
       <View style={{marginTop:5,width:'95%'}}>   
       <View style={{width:'95%',alignContent:'center',marginLeft:10,marginBottom:10}}>
  <Text style={{fontSize:15,color:'grey'}}>ClientID : Log into Smartpractice on the internet and use the 4 digit number at the end of your URL (internet Address) of your login screen 
  </Text>
  </View>
<Button 

        title="Save"
        onPress={LoginButton}
      />
      </View>
        </View>
        </SafeAreaView>
        </KeyboardAwareScrollView>
      );
   
  
       }
      

  const styles = {
    container: {
      
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center',
      marginTop:5
    },
    Label: {
      backgroundColor:'#A6A5A4',
      color:"white",
      textAlign: "center",
       marginTop:2,
       fontSize: 15,
       width:'100%',
       
       
  
    },
    alertmessage:{
      color:'green'
    },
    LabelText: {
      
      backgroundColor:'#A6A5A4',
      color:"white",
      textAlign: "center",
       fontSize: 20,
     
       
       
  
    },
  };

export default Login;

The here is where I am trying to retrieve some of the data (Dashboard.js)

import React, {Component } from 'react'
import { View, Text,Image,TouchableOpacity,StyleSheet,SafeAreaView,} from 'react-native'


import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'

import AsyncStorage from '@react-native-community/async-storage';

function Dashboard ({navigation}){
  
  

   let MyClientID = AsyncStorage.getItem("MyClientID")

   

  console.log(global.mail)
    
      return (
        <KeyboardAwareScrollView keyboardShouldPersistTaps='handled'>
        <SafeAreaView style={styles.container}>
        <View style={{flexDirection:"row"}}>
        <Image source={{uri: 'https://www.site.co.za/images/smartpractice-logo-02.png'}}
       style={{marginTop:5,paddingTop:10
      , height: 80,width:360,flexWrap:'wrap',resizeMode:"contain" }} /> 
<Text style={{textAlign:'center',color:"#4994CF", marginTop:35}}>Beta</Text>
</View>
<Image source={{uri: 'https://www.site.co.za/images/logos/'+MyClientID+'/main-dashboard-logo.png'}}
       style={{marginTop:5,paddingTop:10
      , height: 70,width:'100%',flexWrap:'wrap',resizeMode:"contain",marginLeft:5 }} /> 
<View style={{justifyContent:"center", marginTop:6}}>
 <Text style={styles.DateLabel}>Description</Text>
 
 </View> 
         

          <TouchableOpacity style={styles.ImageButton}
        onPress={() => navigation.navigate('Incidental Time')}
      >
<Image style={{flexWrap:'wrap',resizeMode:"contain",maxHeight:120,maxWidth:120 }}  tintColor='#4994CF' source={require('../../icons/time_log.png')} />
<Text style={styles.TextStyle}>Time Log</Text>

      </TouchableOpacity>
        </SafeAreaView> 
        </KeyboardAwareScrollView>
      
      );
    }
  

    const styles = StyleSheet.create({
    container: {
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center',
    },
    textInput: {
      backgroundColor:'#A6A5A4',
      color:"white",
      textAlign: "center",
       marginTop:5,
       fontSize: 20,
       marginBottom:5
      ,marginLeft:1
  
    },
    DateLabel: {
      backgroundColor:'#A6A5A4',
      color:"white",
      textAlign: "center",
       marginTop:2,
       fontSize: 20,
       paddingLeft:140,
       paddingRight:140,
       width:'100%',
       marginBottom:10
  
    },
    ImageButton: {
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center',
    },
    TextStyle:{
      color:"grey"
    
    }
  });

export default Dashboard;

I have tried setting the items in a useeffect wrapping the values in the setitems in STRING() tried making functions and const with async attached and the await before the set/getitem I have check SO for hours and none of the answers or questions have helped me with this

I seriously dont know what I am doing wrong I followed the asynstorage docs and even copying the code from the docs does not work

I dont get errors, Its been 2 days of struggling with something as simple as local storage Please help


Solution

  • Both getItem and setItem of AsyncStorage are Promise so you need to use await or callback. For setItem, current usage is okay but for getItem, it is essential. You also need to use getItem in useEffect and make MyClientID as a state.

    Try the following code instead of your Dashborad.js:

    import React, {Component} from 'react';
    import {
      View,
      Text,
      Image,
      TouchableOpacity,
      StyleSheet,
      SafeAreaView,
    } from 'react-native';
    
    import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view';
    
    import AsyncStorage from '@react-native-community/async-storage';
    
    function Dashboard({navigation}) {
      const [MyClientID, setMyClientID] = useState('');
    
      useEffect(() => {
        AsyncStorage.getItem('MyClientID').then((myClientID) => {
          setMyClientID(myClientID);
        });
      }, []);
    
      console.log(global.mail);
    
      return (
        <KeyboardAwareScrollView keyboardShouldPersistTaps="handled">
          <SafeAreaView style={styles.container}>
            <View style={{flexDirection: 'row'}}>
              <Image
                source={{
                  uri: 'https://www.site.co.za/images/smartpractice-logo-02.png',
                }}
                style={{
                  marginTop: 5,
                  paddingTop: 10,
                  height: 80,
                  width: 360,
                  flexWrap: 'wrap',
                  resizeMode: 'contain',
                }}
              />
              <Text style={{textAlign: 'center', color: '#4994CF', marginTop: 35}}>
                Beta
              </Text>
            </View>
            <Image
              source={{
                uri:
                  'https://www.site.co.za/images/logos/' +
                  MyClientID +
                  '/main-dashboard-logo.png',
              }}
              style={{
                marginTop: 5,
                paddingTop: 10,
                height: 70,
                width: '100%',
                flexWrap: 'wrap',
                resizeMode: 'contain',
                marginLeft: 5,
              }}
            />
            <View style={{justifyContent: 'center', marginTop: 6}}>
              <Text style={styles.DateLabel}>Description</Text>
            </View>
    
            <TouchableOpacity
              style={styles.ImageButton}
              onPress={() => navigation.navigate('Incidental Time')}>
              <Image
                style={{
                  flexWrap: 'wrap',
                  resizeMode: 'contain',
                  maxHeight: 120,
                  maxWidth: 120,
                }}
                tintColor="#4994CF"
                source={require('../../icons/time_log.png')}
              />
              <Text style={styles.TextStyle}>Time Log</Text>
            </TouchableOpacity>
          </SafeAreaView>
        </KeyboardAwareScrollView>
      );
    }
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
      },
      textInput: {
        backgroundColor: '#A6A5A4',
        color: 'white',
        textAlign: 'center',
        marginTop: 5,
        fontSize: 20,
        marginBottom: 5,
        marginLeft: 1,
      },
      DateLabel: {
        backgroundColor: '#A6A5A4',
        color: 'white',
        textAlign: 'center',
        marginTop: 2,
        fontSize: 20,
        paddingLeft: 140,
        paddingRight: 140,
        width: '100%',
        marginBottom: 10,
      },
      ImageButton: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
      },
      TextStyle: {
        color: 'grey',
      },
    });
    
    export default Dashboard;