TAS1987
TAS1987

Reputation: 91

Code inside Await is not running in Expo App

I have the below code for an expo react app that has worked as expected with the exception of additional code I have recently added - the 'isLoggedIn' contruct. I have added the comment to it that the fuirst console.log is output however the part inside the 'await' never seems to run. Why is this? My intention for the code is to check if a token exists in securestorage and if so is it valid. If so navigate to 'ListsView'. It runs on a simulator but as above, does not run the code inside the await.

import React, { Component, useState } from 'react';
import * as Font from 'expo-font';
import { StyleSheet, Text, View , Button, TextInput, Alert} from 'react-native';
import { AppLoading } from 'expo';
import { Formik } from 'formik';
import { globalStyles } from '../styles/global';
import * as SecureStore from 'expo-secure-store';

const getFonts = () => Font.loadAsync({
    'lobster': require('../assets/fonts/Lobster-Regular.ttf'),
    'nunito': require('../assets/fonts/Nunito-Regular.ttf')
    });

    
export default function LogInForm({ navigation }) {
    const [fontsLoaded ,setFontsLoaded] = useState(false);
    const goToLists  = () => {
      navigation.navigate('ListsView');
    }

    
 const isLoggedIn = () => {
     console.log("-------------");     **NOTE THIS IS TRIGGERED**
        (async () => {
            console.log("xxxxxxxxxx");     **THIS IS NEVER TRIGGERED**
          const token = await SecureStore.getItemAsync('token');
          // Your fetch code
          this.setState({loaded:false, error: null});
          let url = 'https://www.myWebsite.com/api/auth/isLoggedIn';
          let h = new Headers();
          h.append('Authorization', `Bearer ${token}`);
          h.append('Content-Type', 'application/json');
          h.append('X-Requested-With', 'XMLHttpRequest');    
          let req = new Request(url, {
           headers: h,
           method: 'GET'
          });
          fetch(req)
          .then(response=>response.json())
          .then(this.setState({token: isSet}));
          console.log(token);
          console.log("**************");
        })
       }
      
      
      

      
    
    if(fontsLoaded){
        isLoggedIn();  
        return(
            <View style={globalStyles.container}>    
            <View style={globalStyles.centering}>
            <Text style={globalStyles.titleText}>OurShoppingList</Text>
            <View style={globalStyles.logInScreen}>
                <Text style={globalStyles.headingText}>Log In</Text>
                <View>
                    <Formik
                        initialValues={{ email: '', password: ''}}
                        onSubmit={(values) => {
                            SecureStore.deleteItemAsync('token');
                            
                            fetch('https://www.myWebsite.com/api/auth/login', {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json',
                                    'X-Requested-With': 'XMLHttpRequest',
                                },
                                body: JSON.stringify({
                                    email: values.email,
                                    password: values.password,
                                }),
                                })
                            .then(response => response.json())
                            .then(responseJson => {
                                console.log(responseJson)
                                if(responseJson.access_token){

    const setToken = async (token) => {
        await SecureStore.setItemAsync('token', responseJson.access_token);
    };
    setToken ();


                                navigation.navigate('ListsView');
                                } else {
                                    Alert.alert(responseJson.message);
                                }
                                
                            })
                            .catch(error => {
                            console.error(error);
                            alert(error.message);
                            });
                            if(SecureStore.getItemAsync('token')!='') {
                                goToLists;
                            }
                        }}
                    >
                        {(props) => (
                            <View>
                                <Text style={globalStyles.labelText}>Email Address:</Text>
                                
                                    <TextInput
                                    autoCompleteType="username"
                                    style={globalStyles.textInput}
                                
                                    onChangeText={props.handleChange('email')}
                                    value={props.values.email}
                                    />
                                
                                <Text style={globalStyles.labelText}>Password:</Text>
                                <TextInput secureTextEntry={true}
                                style={globalStyles.textInput}
                                onChangeText={props.handleChange('password')}
                                value={props.values.password}
                                />
                                <View style={globalStyles.buttons}>
                                    <Button title='submit' color='orange' onPress={props.handleSubmit} />
                                </View>
                            </View>
                        )}        
                    </Formik>
                    
                </View>
            </View>
            </View>
                <View style={globalStyles.login}>
                </View>           
            </View>
        )
} else {
    return (
      <AppLoading
        startAsync={getFonts}
        onFinish={() => setFontsLoaded(true)}
      />
    );
  }
}

Upvotes: 2

Views: 972

Answers (2)

codemonkey
codemonkey

Reputation: 7905

The code block that starts with (async () => { end ends with }) creates a mere function, but fails to actually run it. Appending () to it will run the function.

So change it to look like this:

(async () => {
            console.log("xxxxxxxxxx");
             ...
             ...
        })()

Note the () at the end, which will trigger the function call.

Upvotes: 3

Hend El-Sahli
Hend El-Sahli

Reputation: 6742

The code you're pointing at is a function-block that will never be executed before you call it

const isLoggedIn = () => {
      console.log('-------------');
      (async () => {
        console.log('xxxxxxxxxx');
        const token = await SecureStore.getItemAsync('token');
        // Your fetch code
        this.setState({ loaded: false, error: null });
        const url = 'https://www.myWebsite.com/api/auth/isLoggedIn';
        const h = new Headers();
        h.append('Authorization', `Bearer ${token}`);
        h.append('Content-Type', 'application/json');
        h.append('X-Requested-With', 'XMLHttpRequest');
        const req = new Request(url, {
          headers: h,
          method: 'GET',
        });
        fetch(req)
          .then(response => response.json())
          .then(this.setState({ token: isSet }));
        console.log(token);
        console.log('**************');
      })(); // <<== those () will exec the code inside the fn-block
    };

OR

const isLoggedIn = async () => {
  console.log('-------------');

  console.log('xxxxxxxxxx');
  const token = await SecureStore.getItemAsync('token');
  // Your fetch code
  this.setState({ loaded: false, error: null });
  const url = 'https://www.myWebsite.com/api/auth/isLoggedIn';
  const h = new Headers();
  h.append('Authorization', `Bearer ${token}`);
  h.append('Content-Type', 'application/json');
  h.append('X-Requested-With', 'XMLHttpRequest');
  const req = new Request(url, {
    headers: h,
    method: 'GET',
  });
  fetch(req)
    .then(response => response.json())
    .then(this.setState({ token: isSet }));
  console.log(token);
  console.log('**************');
};

Upvotes: 2

Related Questions