Call a async function to store accessToken during authentication React-native

346 views Asked by At

I've created a React-native application, using Auth0 authentication (with the auth code sample below):

_onLogin() {
    auth0
        .webAuth
        .authorize({scope: 'openid email', audience: 'https://' + credentials.domain + '/userinfo'})
        .then(credentials => Alert.alert(
                  'Login Success',
                  'AccessToken: ' + credentials.accessToken,
                  [
                    {text: 'OK', onPress: () => console.log('OK Pressed')},
                  ],
                  { cancelable: false },
                  Actions.home()
                ))
        .catch(error => console.log(error));
  }

AND i have this simple function used for store some values into the AsyncStorage (in this case i want store the accessToken given correctly by credentials.accessToken in the function above).

async _storeSomeValues(item, selectedValue) {
    try {
      await AsyncStorage.setItem(item, selectedValue);
    } catch (error) {
      console.log('AsyncStorage error: ' + error.message);
    }
  }

i've check a lot of post, try many ways to use this function into .then(...) statement, but it's always show me this error:

ReferenceError: _storeSomeValues is not defined

Why my function is not defined here?

It's my first react-native application, i never coded with react before.

1

There are 1 answers

1
Poptocrack On

If your _storeSomeValues is in another file, you have to export it from your file and then import it in another one.

First in file1.js

export async function _storeSomeValues(item, selectedValue) {
    try {
      await AsyncStorage.setItem(item, selectedValue);
    } catch (error) {
      console.log('AsyncStorage error: ' + error.message);
    }
  }

And then in your file2.js

import { _storeSomeValues } from 'path/to/file1.js';

Then you can use it anywhere in your file. Do this each time you want to use _storeSopeValues() in another file.