0
import React, { FunctionComponent, useEffect, useState } from "react";
import { StyleSheet, View, ActivityIndicator } from 'react-native';
import { StackNavigationProp } from "@react-navigation/stack";
import { RouteProp } from "@react-navigation/native";
import { FundStackParamsList } from "../../navigation/Params";
import { useTheme } from '../../theme';
import { EdgeInsets, useSafeAreaInsets } from 'react-native-safe-area-context';
import { Endpoints, getTokens } from "../../api";
import PDFView from 'react-native-pdf';

interface ReportViewScreenProps {
  navigation: StackNavigationProp<FundStackParamsList, 'HistoricReportsView'>;
  route: RouteProp<FundStackParamsList, 'HistoricReportsView'>;
}

const HistoricReportViewScreen: FunctionComponent<ReportViewScreenProps> = (props) => {
  const theme = useTheme(),
    edgeInsets = useSafeAreaInsets(),
    style = styles(theme, edgeInsets);

  const [pdfData, setPdfData] = useState<string | null>(null); // State to store Base64 encoded PDF data


  useEffect(() => {
    getTokens()
      .then((token) => {
        fetch(Endpoints.FUND_REPORT_FILE(props.route.params.refID), {
          method: 'GET',
          headers: {
            'Authorization': `Bearer ${token.access}`,
          },
        })
          .then((response) => response.blob())
          .then((blob) => {
            const reader = new FileReader();
            reader.onloadend = () => {
              const base64Data = reader.result as string;
              setPdfData(`data:application/pdf;base64,${base64Data}`);
            };
            reader.readAsDataURL(blob);
          })
          .catch((error) => {
            console.error('Error fetching PDF:', error);
          });
      });
  }, [props.route.params.refID]);
  

  return (
    <View style={style.container}>
    {pdfData ? (
      <PDFView
        source={{ uri: pdfData, cache: true }}
        onLoadComplete={() => console.log('PDF loaded')}
        onError={(error) => console.error('Error loading PDF:', error)}
        style={{ flex: 1 }}
      />
      ) : 
      (
        <ActivityIndicator size="large" color={theme.colors.primary} />
      )}
    </View>
  );
};

const styles = (theme: ReturnType<typeof useTheme>, edgeInsets: EdgeInsets) => StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: theme.colors.background,
  },
  // ...other styles
});

export default HistoricReportViewScreen;

This is my code in react native i'm getting a blog pdf file from backend and i want to show it in my app but when i installed react-native-pdf it's giving me error of Unable to resolve module react-native-blob-util. I'm using "react-native": "0.70.8", and "react-native-pdf": "^6.7.1",

I installed react-native-blob-util but after that i get this error

TypeError: Cannot read property 'getConstants' of null, js engine: hermes
 ERROR  Invariant Violation: Failed to call into JavaScript module method AppRegistry.runApplication(). Module has not been registered as callable. Registered callable JavaScript modules (n = 11): Systrace, JSTimers, HeapCapture, SamplingProfiler, RCTLog, RCTDeviceEventEmitter, RCTNativeAppEventEmitter, GlobalPerformanceLogger, JSDevSupportModule, HMRClient, RCTEventEmitter.
        A frequent cause of the error is that the application entry file path is incorrect. This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native., js engine: hermes
 ERROR  Invariant Violation: Failed to call into JavaScript module method AppRegistry.runApplication(). Module has not been registered as callable. Registered callable JavaScript modules (n = 11): Systrace, JSTimers, HeapCapture, SamplingProfiler, RCTLog, RCTDeviceEventEmitter, RCTNativeAppEventEmitter, GlobalPerformanceLogger, JSDevSupportModule, HMRClient, RCTEventEmitter.

A frequent cause of the error is that the application entry file path is incorrect. This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native., js engine: hermes

I'm using expo go for development.

2 Answers 2

0

Add below code in app.json

"plugins": [
  "@config-plugins/react-native-blob-util",
  "@config-plugins/react-native-pdf"
] 

Install following packages in devDependencies :

"@config-plugins/react-native-blob-util": "^0.0.0",
"@config-plugins/react-native-pdf": "^0.0.0"

Install following package : "react-native-blob-util"

Refer link : https://github.com/expo/examples/tree/master/with-pdf

Sign up to request clarification or add additional context in comments.

Comments

0

I also faced similar kind of error: TypeError: Cannot read property 'getConstants' of null in my react native(0.76.3) project. Just include these three permissions in /app/src/main/AndroidManifest.xml

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

Try uninstalling npm uninstall react-native-blob-util and then installing again npm install react-native-blob-util

Run project npm run android --reset-cache

Following above resolved my issue and also I am able to download files.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.