0
votes

Maybe my question is just a geek mistake. Let's suppose a simple form class that uses RNFS (itinance/react-native-fs)

class myform1 extends Component<{}> {

  constructor(props) {
    super(props);

    this.state = {
      loading: false,
    };
  }

  async _myfunction(dir_name) {

    try {

      const response = await RNFS.readDir(RNFS.DocumentDirectoryPath + '/' + dir_name);

      const r = await response;

      console.log(r); //-> here, it show the correct result

      return r;

    } catch(e){ console.log(e) }

  }

This console.log prints the correct result: objects with the files in directory name. But if I try to console.log() the result in render(), on class, the result is not showable, but just the promise:

Promise {_40: 0, _65: 0, _55: null, _72: null}

Here is the code for my class:

componentDidMount(){

    ...some_stuffs_to_do...

}
render() {
      return(
        <View>
            {
                some_variable.map((key, index) => {

                const test = this._myfunction(dir_name);

                console.log('on form: ');
                console.log(test); //-> here, it show "Promise {_40: 0, _65: 0, _55: null, _72: null}"
            }
            ...

            <Text>Just example</Text>
        </View>
     );
}

I try a lot of things to solve this, but I did not make it.

Any good soul to help me, please?

Thanks a lot

1
An async function will always return a Promise. So test is a promiseNick Parsons
Add await before calling _myFunction since it's a Promise. const test = await this._myfunction(dir_name); But this is not a good approach. Try to get _myfunction's responses and outside of the render method.Gev

1 Answers

0
votes

The return value of an async method will always be a Promise. So the value returned by _myfunction is a Promise. In your componentDidMount() method, you can extract the value in the promise returned by _myfunction using .then(). You can then update the state's test property and use that states test property in your render() method:

...
componentDidMount(){
  // other code...

  Promise.all(some_variable.map((key, index) => {
    return this._myfunction(dir_name);
  }).then((mapped_arr) => {
    this.setState({mapped_arr});
  }); 
}

render() {
  return(
    <View>
      {this.state.mapped_arr}
    </View>
  );
}
...