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
JavaScript
x
26
26
1
const _userLogin = () => {
2
fetch(URLs._login, {
3
method: "POST",
4
headers, body,
5
})
6
}).then((response) => response.json())
7
.then((result) => {
8
if(result.message !== "Unauthorized / Access Token Expired" && result.message !== "The given data was invalid."){
9
storeData(result.access_token, result.token_type);
10
navigation.navigate('HomeScreen');
11
} else {
12
Alert.alert("Error", result.message);
13
}
14
});
15
};
16
17
const storeData = async (accessToken, tokenType) => {
18
try {
19
await AsyncStorage.setItem('@access_token', accessToken);
20
await AsyncStorage.setItem('@token_type', tokenType);
21
await AsyncStorage.setItem('@user_auth', tokenType + " " + accessToken);
22
} catch (e) {
23
console.log(e);
24
}
25
}
26
Home.js [UPDATE]
JavaScript
1
48
48
1
const [inputs, setInputs] = React.useState({
2
userToken: '',
3
userPointsBalance: '',
4
expiringOn: '',
5
});
6
7
useEffect (() => {
8
_dashboard();
9
})
10
11
const getToken = async () => {
12
inputs.userToken = await AsyncStorage.getItem('@user_auth');
13
}
14
15
const _dashboard = () => {
16
getToken();
17
fetch(URLs._dashboard, {
18
method: "GET",
19
headers: {
20
'Authorization': inputs.userToken,
21
'Content-Type': 'application/json',
22
},
23
}).then((response) => response.json())
24
.then(async (result) => {
25
storeData(result.code, result.name, result.member_name, result.user_points_balance, result.expiring_on, result.status, result.token_id);
26
getData();
27
});
28
};
29
30
const storeData = async (code, name, memberName, userPointsBalance, expiringOn, status, tokenId) => {
31
try {
32
await AsyncStorage.setItem('@user_points_balance', userPointsBalance.toString());
33
await AsyncStorage.setItem('@expiring_on', expiringOn.toString());
34
35
} catch (e) {
36
console.log(e);
37
}
38
}
39
const getData = async () => {
40
const userPointsBalance = await AsyncStorage.getItem('@user_points_balance');
41
const expiringOn = await AsyncStorage.getItem('@expiring_on');
42
setInputs({userPointsBalance: userPointsBalance, expiringOn: expiringOn});
43
}
44
45
return (
46
<Text>{inputs.expiringOn}<Text>
47
)
48
Advertisement
Answer
i hope it works
JavaScript
1
11
11
1
.then(async(result) => {
2
if(result.message !== "Unauthorized / Access Token Expired" && result.message !== "The given data was invalid."){
3
await storeData(result.access_token, result.token_type)
4
.then(res=>
5
navigation.navigate('HomeScreen')
6
)
7
} else {
8
Alert.alert("Error", result.message);
9
}
10
});
11