I'm working on a React Native project where I need to fetch data from the backend, zip it, and download the zipped file using jszip and rn-fetch-blob. The code I've implemented is resulting in an "Unexpected Token" error, and I'm seeking guidance to understand and resolve this issue.


import {useState, useEffect} from 'react';
import RNFetchBlob from 'rn-fetch-blob';
import JSZip from 'jszip';
import {Toast} from 'native-base';
const useDownloadZipNestedArray = async (data: any[]) => {
  try {
    const allUrlsData: {url: string; path: string}[] = [];
    const handleRecursion = (data: any[], folder: string) => {
      data?.forEach(item => {
        if (item?.naacFiles?.length) {
          item?.naacFiles?.forEach((inner: any) => {
            allUrlsData?.push({
              path: `${folder}/${item?.title}/${inner?.title}`,
              url: inner?.documentUrl,
            });
          });
        }
        if (item?.internalFolder?.length) {
          handleRecursion(item?.internalFolder, `${folder}/${item?.title}`);
        }
      });
    };

    data?.forEach(item => {
      if (item?.naacFiles?.length) {
        item?.naacFiles?.forEach((inner: any) => {
          allUrlsData?.push({
            path: `${item?.title}/${inner?.title}`,
            url: inner?.documentUrl,
          });
        });
      }

      if (item?.internalFolder?.length) {
        handleRecursion(item?.internalFolder, item?.title);
      }
    });
    // console.log(allUrlsData);
    const zip = new JSZip();

    await Promise.all(
      allUrlsData?.map(
        async item =>
          new Promise(async (resolve, reject) => {
            try {
              console.log('Fetching data for file:', item.url);

              // Fetch the image as a blob
              const response = await fetch(item?.url);

              if (!response.ok) {
                console.error(
                  'Failed to fetch data for file:',
                  item.url,
                  response.status,
                  response.statusText,
                );
                resolve(false);
                return;
              }

              const imageBlob = await response.blob();

              const fileExtension = item?.url?.split('.').at(-1);

              // Extract the filename from the URL (assuming it's the last part after '/')
              const filename =
                item?.path + '.' + fileExtension ||
                item?.url?.substring(item?.url?.lastIndexOf('/') + 1);

              // Add the blob to the ZIP archive with the extracted filename
              zip.file(filename, imageBlob);
              resolve(true);
            } catch (error) {
              console.error('Error fetching data for file:', item.url, error);
              resolve(false);
            }
          }),
      ),
    );

    const zipBlob = await zip.generateAsync({type: 'blob'});
    console.log({zipBlob});
    // const {config, fs} = RNFetchBlob;
    // let DOCUMENT_DIR = fs.dirs.DownloadDir;
    // let date = new Date();

    // let options = {
    //   fileCache: true,
    //   addAndroidDownloads: {
    //     useDownloadManager: true,
    //     notification: true,
    //     title: 'Export Zip',
    //     path:
    //       DOCUMENT_DIR +
    //       '/Erp/' +
    //       Math.floor(date.getTime() + date.getSeconds() / 2) +
    //       '.zip',
    //     description: 'Downloading....',
    //   },
    // };
    // console.log({options});
  } catch (e) {
    console.log(e);
  }
};

export default useDownloadZipNestedArray;



//here When I press this button 
 <Pressable
   onPress={() => {checkPermission();}}
   p={4}
   justifyContent={'center'}
  alignItems={'center'}
   borderRadius={'full'}
   bgColor={COLORS.secondary}
  position={'absolute'}
  shadow={2}
  bottom={5}
  right={5}>
 <AppIcon
  MaterialCommunityIconsName="download"
  size={25}
  color={'white'}
 />
</Pressable>

//here I handle the permissions
 const checkPermission = async () => {
    if (Platform.OS === 'android') {
      try {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
          {
            title: 'Storage Permission Required',
            message: 'Needs access to your storage to download',
            buttonPositive: 'OK',
          },
        );
        if (granted === PermissionsAndroid.RESULTS.GRANTED) {
          console.log('Storage Permission Granted.');
          useDownloadZipNestedArray(naacData?.data?.data);
        } else {
          Alert.alert('Storage Permission Not Granted');
        }
      } catch (err) {
        console.warn(err);
      }
    }
  }; 
`

Environment:

  • React Native version: 0.72.1
  • Packages: "rn-fetch-blob": "^0.12.0", "jszip": "^3.10.1"
  • Issue: Encountering "Unexpected Token" error with the provided code. Seeking insights into the possible causes and solutions for this error. Possible Unhandled Promise Rejection (id: 65)

I expected the zipping and downloading process to work smoothly, resulting in a downloadable zipped file containing the converted data.

0

There are 0 answers