androidreact-nativeunlinkreact-native-fs

React Native Android: Deleting file


I'm making a gallery style app where I need to add the functionality of deleting images.

I'm using the RNFS library, specifically the unlink function. When finished the function throws no errors but it does not delete the file from my phone.

To isolate the problem, I create a new app using the AwesomeProject template and added these lines of code :

import RNFS from 'react-native-fs';
import {PermissionsAndroid} from 'react-native';

In App.tsx.

  const usEffectFunction = async () => {
    const permission = PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE;

    const hasPermission = await PermissionsAndroid.check(permission);
    if (!hasPermission) {
      await PermissionsAndroid.request(permission);
    }

    RNFS.unlink('/storage/emulated/0/Download/1.pdf')
      .then(() => {
        console.log('file deleted');
      })
      .catch((e: any) => console.log(e));
  };

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

In App.tsx inside the App component.

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES"/>
<uses-permission android:name="android.permission.READ_MEDIA_VIDEO"/>

In AndroidManifest.xml.

All this code does is ask for permission to write to storage and then delete a file in my file system.

If the path doesn't exist I get "[Error: File does not exist]" message,

If the path is correct I get "file deleted" and no error, but the file doesn't get deleted from my device, I can still find it using the Android file manager.


Solution

  • After some research here is the information I learned.

    I was able to solve my problem by creating my own npm package called react-native-delete-media.

    It's a simple module that has a single function deletePhotos which takes an array of uris and asks the Android OS to delete it.