Nihilarian
Nihilarian

Reputation: 1198

React Native Async Await returns null when called

I am new to React Native and coming from a PHP background.

storage.js

const getToken = async () => {
    try {
        return await SecureStore.getItemAsync(authKey);

    } catch (error) {
        console.log('Error getting auth token:', error)
    }
}

Client.js

const authToken = async () => await storage.getToken();

console.log('clientjs authtoken -->', authToken());

const apiClient = create({
    baseURL: 'http://www.example.com/mobile',
    headers: { Authorization: 'Bearer ' + authToken() },
});

This console.log shows me this: clientjs --> {"_U": 0, "_V": 0, "_W": null, "_X": null}.

I've also simply tried writing: const authToken = storage.getToken(); but getting the same result. What am I doing wrong? Any help would be appreciated.

Upvotes: 1

Views: 926

Answers (1)

Abe
Abe

Reputation: 5508

Since authToken is marked as an async method, its result needs to be awaited or .thened.

const token = await authToken();
const apiClient = create({
    baseURL: 'http://www.example.com/mobile',
    headers: { Authorization: 'Bearer ' + token },
});

The above syntax relies on being inside an async method. You can use .then in a synchronous context:

let apiClient;

authToken().then(token => {
  apiClient = create({
    baseURL: 'http://www.example.com/mobile',
    headers: { Authorization: 'Bearer ' + token },
  });
});

{"_U": 0, "_V": 0, "_W": null, "_X": null} represents an unresolved promise. I wish this was clearer, as it causes a lot of confusion in learning javascript.

Edit: another method to export the client: export a function that returns it.

const getClient = async () => {
  const token = await authToken();
  const apiClient = create({
    baseURL: 'http://www.example.com/mobile',
    headers: { Authorization: 'Bearer ' + token },
  });
  return apiClient;
});

export default getClient;

And then in the component:

  getClient.then(client => {
    client.post( // ...

Upvotes: 2

Related Questions