S.B
S.B

Reputation: 329

Read files in directory - Expo FileSystem

I am using below code to download a selected PDF document from an API:

DownloadDocument = (docUri) => {

FileSystem.makeDirectoryAsync(FileSystem.documentDirectory + 'app_docs/', { intermediates: true });

FileSystem.downloadAsync(
  ' https://example.com/library/documents/' + docUri,
  FileSystem.documentDirectory + 'app_docs/' + docUri
)
  .then(({ uri }) => {
    console.log('Finished downloading to ', uri);
  })
  .catch(error => {
    console.error(error);
  });

}

Is there a way i can loop round all the documents that have been downloaded into the app_docs folder?

I've been trying to use FileSystem.readDirectoryAsync(FileSystem.documentDirectory + 'app_docs') but not having much joy.

Upvotes: 2

Views: 7926

Answers (1)

S.B
S.B

Reputation: 329

I've solved the problem by doing the following:

state = {
  docsList: [],
}

 componentDidMount() {
   this._getAllFilesInDirectory();
 }

_getAllFilesInDirectory = async() => {
   let dir = await FileSystem.readDirectoryAsync(FileSystem.documentDirectory + 'app_docs');

   dir.forEach((val) => {
     this.state.docsList.push(FileSystem.documentDirectory + 'app_docs/' + val);
});

   await this.setState({docsList: this.state.docsList, loading: false});
}

Then in the render:

    {this.state.docsList.map((val, key) => (
        <Text key={key}>{val}</Text>
    ))}

This is a basic example to help anyone along that is struggling to get a loop working straight from the directory folder. Hopefully it helps.

Upvotes: 7

Related Questions