I am using componentWillMount in react-native to get data from API. But when I tried to get the token stored while login. It cannot work. I have no idea whats the problem/
componentWillMount(){
let token = this.getData
fetch('http://192.168.0.125:8887/api/auth/activities/index',{
method: 'POST',
headers:{
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer '. token,
},
})
.then((response) => response.json())
.then((res) => {
//console.log(res)
})
.catch((e) => console.log('Error: ', e))
}
getData = async () => {
let token =''
try{
token = AsyncStorage.getItem('id_token')
console.log(token)
}catch (error) {
console.log('AsyncStorage error: ' + error.message);
}
return token
}
Don't make the api call inside ComponentWillMount. Do that inside ComponentDidMount. And for your problem - Try await AsyncStorage.getItem('id_token') because AsyncStorage is a promise.
or you can do
componentDidMount(){
AsyncStorage.getItem('id_token').then(this.getData)
}
getData=(token)=>{
fetch('http://192.168.0.125:8887/api/auth/activities/index',{
method: 'POST',
headers:{
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer '+ token,
},
})
.then((response) => response.json())
.then((res) => {
//console.log(res)
})
.catch((e) => console.log('Error: ', e))
}