Search code examples
javascriptreactjsreact-nativeasync-awaitreact-lifecycle-hooks

How to call an async function in textinput?


How to call an async function with in textinput?

getTxt = async () => {

    filetxt = 'abc';
    currentFileName = this.props.navigation.getParam("currentFileName");
    console.log(currentFileName);

    try {

        filetxt = FileSystem.readAsStringAsync(`${FileSystem.documentDirectory}${currentFileName}.txt`, { encoding: FileSystem.EncodingTypes.UTF8 });

        console.log(filetxt);

    } catch (error) {
        console.log(error);
    }

    return filetxt;
}

render() {

    return (
        <View style={{ flex: 1 }}>
            <TextInput
                multiline = {true}
                style={{ margin : 10 }}
            >{ await this.getTxt() }
            </TextInput>
            <Button onPress = { this.FunctionToOpenFirstActivity } title = 'Save'/>
        </View>
    );
}

There is an error "await is a reserved words", anyknow knows?


Solution

  • You need to re-arrange the code to get desired result. You can't use await in render() which is not async function. If you call async function getTxt without await, it will return a promise. So the filetext will be empty at the time of rendering. You need to make use of state to automatically re-render when value changes.

    // Initialise filetext with state
    constructor(props) {
        super(props);
        this.state = {
          filetext: ""
        };
      }
    // Make componentWillMount async and invoke getTxt with await
    async componentWillMount() {
     let text = await this.getTxt();
     this.setState({ filetext: text });
    }
    
    //Access filetext from the state so that it will automatically re-render when value changes
    
    render() {
    
        return (
            <View style={{ flex: 1 }}>
                <TextInput
                    multiline = {true}
                    style={{ margin : 10 }}
                >{ this.state.filetext }
                </TextInput>
                <Button onPress = { this.FunctionToOpenFirstActivity } title = 'Save'/>
            </View>
        );
    }