0

So, I am trying to get JWT token INITIAL_STATE of my reducer.

I am using 'expo-secure-store' package for store token using expo

But when i try to getToken it is returning me a promise instead of token value, like below:

AuthUser: Promise {
  "_U": 0,
  "_V": 1,
  "_W": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjo3LCJ1c2VybmFtZSI6InNocmVleWFjaEBzYXR2aXguY29tIiwiZW1haWwiOiJzaHJlZXlhY2hAc2F0dml4LmNvbSI",
  "_X": null,
}

Here is my code for retrieving token:

import * as SecureStorage from 'expo-secure-store';

const _retrieveData = async () => {
  try {
    const data = await SecureStorage.getItemAsync('token');
    return data;
  } catch (error) {
    console.log(error);
  }
};

const INIT_STATE = {
  loader: false,
  alertMessage: '',
  successMessage: '',
  showMessage: false,
  initURL: '',
  authUser: _retrieveData().then((token) => token),
  tempAuth: '',
  currentScreen: 0,
  showSuccessMessage: false,
  currentUser: null,
  sendOTP: false,
};

I have tried other StackOverflow solution from here, here and here, but not able to get token as string value.

Kartikey
  • 4,516
  • 4
  • 15
  • 40
Shreeya Chhatrala
  • 1,441
  • 18
  • 33

1 Answers1

2

In the export object change,

authUser: _retrieveData().then(token => token),

to

authUser: _retrieveData,

Now wherever you want to call this function, use it like this

const response = await authUser();
console.log(response) 
// This will be the required token

For Reference,

Have a look at the storage object exported from here

You see, I passed a reference to the function here.

And used it here as mentioned above

Kartikey
  • 4,516
  • 4
  • 15
  • 40
  • @AndroidPlayer_Shree Happy to Help! If your issue is resolved consider accepting the answer as it may help users in the future. Thanks – Kartikey Sep 06 '21 at 18:08