Search code examples
javascriptreactjsreact-nativeexpofilesystemobject

How to extract Data from a Promise react Native


I am using Expo for this project where I am allowing the user to upload a file and I want to save that file as a String where I will later parse it. I am using expo-document-picker and Expo-File-System.

I thought I could use the FileSystem library to read the uri file as a string with the function: readAsStringAsync()

This is the output I am getting:

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

This is the code I have so far:

export default function FileUploaded({navigation}) {
let userOut
const pickDocument = async() => {
    try{
        let input = await DocumentPicker.getDocumentAsync({
            type:'text/plain',
        })
        userOut = FileSystem.readAsStringAsync(input.uri)
        //console.log(userOut)
        //time to delete information
        //FileSystem.deleteAsync(userOut)
    }
    catch (error){
        throw(error)
    }
}

return (
    <View>
        <TouchableOpacity 
        style={{position:'absolute', top:100}}
        title='Upload Documnet (.txt only)'
        onPress= {()=>pickDocument()}>
            <Text>What is happening</Text>
        </TouchableOpacity>
        
    </View>
) 

}


Solution

  • As the docs says:

    Returns

    A Promise that resolves to a string containing the entire contents of the file.

    Since it returns a Promise, you should use await or .then():

    userOut = await FileSystem.readAsStringAsync(input.uri)
    

    Also, you don't need to catch the error if you are just throwing it again.