Reputation: 123
I am trying to access a rest api endpoint that requires you send it a token with react native. For development purposes am storing it in Async Storage wrapped in a APIToken class with two methods that set or get the token and returns the token.
import {AsyncStorage} from 'react-native';
class APIToken {
constructor(){}
async get(){
try {
const token = await AsyncStorage.getItem('api_token');
if (token !== null) {
// We have data!!
console.log(token);
return token
}
} catch (error) {
// Error retrieving data
}
//return null
}
async set(token){
try {
await AsyncStorage.setItem('api_token', token);
return token
} catch (error) {
// Error saving data
}
//return null
}
}
export default APIToken
So I am using the async functions in hopes that I can resolve the key to a string value instead of a promise. When I call the api using these functions I get the key returning correctly in the console but in the headers it returns as a promise.
const key = function() {
const k = (new APIToken()).get()
return k
}
const api = axios.create({
baseURL: Config.API_URL_V1,
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + key(),
'Cache-Control': 'no-cache'
}
});
What is returned from the console from the ApiToken class
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9uZXQtYXBwMS5oZXJva3VhcHAuY29tXC9hcGlcL3YxXC9sb2dpbiIsImlhdCI6MTU2NDkzMTcxMywiZXhwIjoxNTY0OTM1MzEzLCJuYmYiOjE1NjQ5MzE3MTMsImp0aSI6InpUMzV5NU43Q2NGejRTanciLCJzdWIiOiI1ZDMzNTcwNDgwMmRmMDAwMDc2YmFkOTciLCJwcnYiOiI4N2UwYWYxZWY5ZmQxNTgxMmZkZWM5NzE1M2ExNGUwYjA0NzU0NmFhIn0.nhDmwYWS5NaGifg-atwEw4DwUNvvpv-I_Ntw5L9kmCc
The Authorization header in the call:
Authorization: "Bearer [object Object]"
I have tried so many different thing and have been unable to get the key so I can use it in my api calls without getting 403 due to the key no returning correctly. Any help would be great.
Upvotes: 0
Views: 803
Reputation: 750
You are wrong in key function and api function when call key you don't use await and in key when call get token you don't use await too. You need convert both function to async or using promise then. Below code will solve you problem. Please try it.
const key = async function () {
const apiToken = new APIToken();
const k = await apiToken.get();
return k;
}
const api = async function () {
var token = await key();
return axios.create({
baseURL: Config.API_URL_V1,
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token,
'Cache-Control': 'no-cache'
}
});
}
async function fetchEvents() {
let request = await api();
return request.get(Config.API_URL_V1 + 'events').catch((error) => console.log(error.response))
}
Upvotes: 1