Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

425
Vistas
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>
)
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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);
        }
    });
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda