Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

424
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda