3

I am using react-native-fs for reading files in device's external storage. I want to get all pdf books stored in an android device and list them in the screen. Searched in google, read docs in react-native-fs but not succeed getting all pdf books. please help if something wrong with my code.

What I'm doing wrong?

Here is my code.

import React, { useState, useEffect } from 'react';
import {
  Alert,
  StyleSheet,
  Text,
  View,
  Dimensions,
  ImageBackground,
  ScrollView,
  PermissionsAndroid,
  ActivityIndicator,
} from 'react-native';

import RNFS from 'react-native-fs';
import BookOffline from '../components/BookOffline';

const MyBooks = ({ navigation }) => {
  // collecting data from device
  const [books, setBooks] = useState([])
  const [bookList, setBookList] = useState([]);

  useEffect(() => {
    getPermission();
  }, []);


  const getPermission = async () => {
    try {
      PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE
      ).then(granted => {
        if (granted === PermissionsAndroid.RESULTS.GRANTED) {
          readStorage();
        } else {
          //If permission denied then show alert
          Alert.alert('Not Granted storage_permission');
          navigation.goBack();
        }
      });
    } catch (err) {
      //To handle permission related issue
      console.log('error', err);
    }
  };


  const readStorage = async () => {
    let list2 = [];
    await RNFS.readDir(RNFS.ExternalStorageDirectoryPath) // On Android, use "RNFS.DocumentDirectoryPath" (MainBundlePath is not defined)
      .then(result => {
        result.forEach((item, index) => {
          // console.log(index, item)
          if (item.name.endsWith('.pdf')) {
            setBooks([...books, item])
          }
          else if (item.isDirectory()) {
            RNFS.readDir(item.path)
              .then(result => {
                list2 = result.filter((item) => item.name.endsWith('.pdf'))
                setBooks([...books, ...list2])
              }).catch((error) => {
                console.log(error)
              })
          }
        });
        setBookList(books)
        console.log("bookList", bookList)
      })
      .catch(error => {
        console.log(error);
      });
  };


  return bookList.length == 0 ? (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Text>Loading...</Text>
      <ActivityIndicator size="large" />
    </View>
  ) : (
    <View style={{ justifyContent: 'center', alignItems: 'center' }}>
      <ImageBackground
        source={require('../assets/images/tech-dark-design.jpg')}
        resizeMode="cover"
        style={{ width: '100%' }}>
        <ScrollView style={styles.images}>
          {bookList.map((item, index) => {
            return <BookOffline data={item} key={index} />;
          })}
        </ScrollView>
      </ImageBackground>
    </View>
  );
};

export default MyBooks;

const styles = StyleSheet.create({
  container: {
    height: Dimensions.get('window').height - 110,
    //  padding: 5,
  },
  list: {
    width: '100%',
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 1,
    },
    shadowOpacity: 0.2,
    shadowRadius: 1.41,
    elevation: 2,
    marginBottom: 1,
  },
});
  • What debugging steps have you taken? Tell us with an [edit] how you have determined that it is not working as you expect. –  May 27 '22 at 14:51
  • Actually its working and console logs are also fine but when I iterate for filtering I am only getting last file from all the files in my list. – Abdul rehman Tahir May 28 '22 at 09:52
  • "Tell us with an [edit] how you have determined that it is not working as you expect". Show us _in the question_ what you want to do, show what you tried, and show the result you get. Be as clear as you can, and include relevant details _in the body of the question_. SO is not a debugger, and is actually a terrible code debugger. The expectation is you show what you have tried. –  May 31 '22 at 15:36

0 Answers0