1

Is it possible to use async/await outside of classes? For example I use AsyncStorage to store access token and want to get this token before StackNavigator will be initialized.

container.js

import React from 'react';
import { StackNavigator } from 'react-navigation';
import PairingView from '../components/PairingView';
import MainView from '../components/MainView';
import { getTokenFromStorageAsync } from '../helpers/asyncStorageHelper';

const accessToken = getTokenFromStorageAsync().done();
console.log(accessToken);   <---------- undefined

const AppNavigator = StackNavigator({
  PairingRoute: {
    screen: PairingView
  },
  MainRoute: {
    screen: MainView
  }
}, {
  initialRouteName: (accessToken == null) ? 'PairingRoute' : 'MainRoute',
  initialRouteParams: {
    token: accessToken
  }
});

const App = () => (
  <AppNavigator />
);

export default App;

asyncStorageHelper.js

import { AsyncStorage } from 'react-native';

export const getTokenFromStorageAsync = async () => {
  try {
    const value = await AsyncStorage.getItem('@nfs:token');
    console.log(value);   <---------- access token
    if (value != null)
      return value;
  } catch (err) {
    console.error(err);
  }
  return undefined;
};
4
  • 1
    const accessToken = await getTokenFromStorageAsync(); Commented Jun 23, 2017 at 10:21
  • @ponury-kostek await can be used only with async function Commented Jun 23, 2017 at 10:26
  • Sorry my mistake. So change it to getTokenFromStorageAsync().then(token => console.log(token)); Commented Jun 23, 2017 at 10:28
  • async/await is part of this year's release (ES2017) not of last years release (ES7/ES2016). Please read tag descriptions. Commented Jun 25, 2017 at 19:13

2 Answers 2

2

Solved the problem.

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      accessToken: 'fetching'
    };

    this._loadAccessToken();
  }

  _loadAccessToken = async () => {
    const token = await getTokenFromStorageAsync();
    this.setState({ accessToken: token });
  }

  render() {
    if (this.state.accessToken === 'fetching')
      return null;

    const AppNavigator = StackNavigator({
      PairingRoute: {
        screen: PairingView
      },
      MainRoute: {
        screen: MainView
      }
    }, {
      initialRouteName: (this.state.accessToken == null) ? 'PairingRoute' : 'MainRoute',
      initialRouteParams: {
        token: this.state.accessToken
      }
    });

    return <AppNavigator />;
  }
}

export default App;
Sign up to request clarification or add additional context in comments.

2 Comments

Can you explain what you did to fix it?
@Noitidart so, in question i tried to get value from AsyncStorage outside of component. It will not work, because await can't be used without async function. I just move it inside component and do whatever I want.
0
getTokenFromStorageAsync().then(accessToken => {
    console.log(accessToken);
    // ...
});

or

// ...
export default (async () => {

    const accessToken = await getTokenFromStorageAsync();
    console.log(accessToken);

    const AppNavigator = StackNavigator({
      PairingRoute: {
        screen: PairingView
      },
      MainRoute: {
        screen: MainView
      }
    }, {
      initialRouteName: (accessToken == null) ? 'PairingRoute' : 'MainRoute',
      initialRouteParams: {
        token: accessToken
      }
    });

    const App = () => (
      <AppNavigator />
    );

    return App;

})()

As you can see you have to export a promise that resolves with your App, instead of exporting your App directly.

Edit:

import { AppRegistry } from 'react-native';
import App from './app/container';
(async () => {
    let ResolvedApp = await App()
    AppRegistry.registerComponent('someappname', () => ResolvedApp);
    // ...
})()

18 Comments

and how can it be used with AppNavigator?
I don't understand your question.
'import' and 'export' may only appear at the top level
Oh, I see what you mean. You'll have to export a promise that resolves wihtout your App then.
as well as if i import getTokenFromStorageAsync as Promise. I want to do this without .then or .done.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.