How to call an async function from other file with React Native?

Viewed 62

I have 2 files:

// index.js

export async function main(){
  // Here is a set of functions with which
  // I get an array with different data. these functions
  // are also asynchronous, so you should use
  // "wait"; and hence this function is also
  // async. That array is the "resultado" variable.
  return Promise.resolve(resultado.join("\n"));
}
// App.js

import React, { useState } from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';
import Constants from 'expo-constants';

import { main } from './Backend/index'; 

export default function App() {
  const [someVal, setSomeVal] = useState('');
  (async () => {
    const awaitedVal = await main()
    setSomeVal(awaitedVal)
  })();
  return (
    <View style={styles.container}>
      <Text style={styles.paragraph}>
        <a> {someVal} </a>
      </Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});

As it is, it doesn't work (because being the function asynchronous, it doesn't work like that). I have two different files. How do I do it?

UPDATED: Now, a new error appears.

The error

1 Answers

main() returns a promise which is not resolved and react can not show it's value. what you can do is to add a useState hook and put that between curly braces.

Then inside an async IIFE set value of useState to result of awaited main()

This is App.js

import logo from './logo.svg';
import './App.css';
import { useState } from 'react'
import { main } from './main';
function App() {
  const [someVal, setSomeVal] = useState('');
  (async () => {
    const awaitedVal = await main()
    setSomeVal(awaitedVal)
  })();
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          {someVal} Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

Instead of async, await and IIFE you can also use .then

main().then(res => {
    setSomeVal(res)
  })

And this is main.js

export async function main() {
    return Promise.resolve("Hello");
}

Related