Skip to content
Advertisement

React Native – Variable does not update correctly when retrieving data from AsyncStorage

I’m trying to store and get data that I fetch from an API. The user is supposed to get a token on the login screen, and the token will be shown in an Alert dialog on home screen when the user press a button. But the token is not shown in the Alert dialog. the token is shown after I reload(not refresh the app. I used Live Server extension) the screen three times.

Login.js

const _userLogin = () => { 
        fetch(URLs._login, {
            method: "POST",
            headers, body,
            })
        }).then((response) => response.json())
        .then((result) => {
            if(result.message !== "Unauthorized / Access Token Expired" && result.message !== "The given data was invalid."){
                storeData(result.access_token, result.token_type);
                navigation.navigate('HomeScreen');
            } else {
                Alert.alert("Error", result.message);
            }
        });
    };

const storeData = async (accessToken, tokenType) => {
        try {
            await AsyncStorage.setItem('@access_token', accessToken);
            await AsyncStorage.setItem('@token_type', tokenType);
            await AsyncStorage.setItem('@user_auth', tokenType + " " + accessToken);
        } catch (e) {
          console.log(e);
        }
    }

Home.js [UPDATE]

const [inputs, setInputs] = React.useState({
        userToken: '',
        userPointsBalance: '',
        expiringOn: '',
    });

useEffect (() => {
    _dashboard();
})

const getToken = async () => {
        inputs.userToken = await AsyncStorage.getItem('@user_auth');
    }

const _dashboard = () => {
        getToken();
        fetch(URLs._dashboard, {
            method: "GET",
            headers: {
                'Authorization': inputs.userToken,
                'Content-Type': 'application/json',
            },
        }).then((response) => response.json())
        .then(async (result) => {
            storeData(result.code, result.name, result.member_name, result.user_points_balance, result.expiring_on, result.status, result.token_id);
            getData();
        });
    };

    const storeData = async (code, name, memberName, userPointsBalance, expiringOn, status, tokenId) => {
        try {
            await AsyncStorage.setItem('@user_points_balance', userPointsBalance.toString());
            await AsyncStorage.setItem('@expiring_on', expiringOn.toString());
            
        } catch (e) {
          console.log(e);
        }
    }
const getData = async () => {
    const userPointsBalance = await AsyncStorage.getItem('@user_points_balance');
    const expiringOn = await AsyncStorage.getItem('@expiring_on');
    setInputs({userPointsBalance: userPointsBalance, expiringOn: expiringOn});
}

return (
   <Text>{inputs.expiringOn}<Text>
)

Advertisement

Answer

i hope it works

 .then(async(result) => {
        if(result.message !== "Unauthorized / Access Token Expired" && result.message !== "The given data was invalid."){
         await storeData(result.access_token, result.token_type)
         .then(res=>
           navigation.navigate('HomeScreen')
           )
         } else {
            Alert.alert("Error", result.message);
        }
    });
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement