2

I'm working on my AuthService for my react-native frontend. I get data from backend for example an access token and then I pass it to my AuthService to store it with expo secure store. It looks like this (authService.js):

import * as SecureStore from "expo-secure-store";
import jwtDecode from "jwt-decode";

export async function storeJwt(jwt) {
  await SecureStore.setItemAsync("vpacctok", jwt);
}

export async function getJwt() {
  return await SecureStore.getItemAsync("vpacctok");
}

export async function logout() {
  return await SecureStore.deleteItemAsync("vpacctok");
}

export async function getCurrentUser() {
  try {
    const jwt = await SecureStore.getItemAsync("vpacctok");
    if (jwt) {
      return jwtDecode(jwt);
    } else {
      return null;
    }
  } catch {
    return null;
  }
}

export default {
  storeJwt,
  logout,
  getJwt,
  getCurrentUser,
};

In my components I can simply call this functions which returns my user or my jwt:

if (auth.getCurrentUser()) {
    navigation.navigate(routes.NEWS_SCREEN);
  }

But since I'm working with secure-store from expo I have async functions and auth.getCurrentUser() for example is not returning my user object instead it returns and stupid Promise.

I found solutions to access the data, but only if I use this functions directly inside my components. This is not what I want. I need a AuthService like this, which I can reuse in several components.

How can I solve this? Thank you guys!

wyndham007
  • 181
  • 3
  • 14
  • 1
    Haha "instead it returns a stupid Promise" ... the amount of times we've all shared that sentiment – sgarza62 Oct 06 '20 at 18:47

1 Answers1

2

If you're calling it from an async function, you can use await like this:

const user = await auth.getCurrentUser();
if (user) navigation.navigate(routes.NEWS_SCREEN);

Otherwise, you can use .then like this:

auth.getCurrentUser().then(user => {
  if (user) navigation.navigate(routes.NEWS_SCREEN);
  // continue logic here
});

In both these cases, user will be whatever is returned within your getCurrentUser async function.

sgarza62
  • 5,998
  • 8
  • 49
  • 69